Euler Problem no.30 with Python

This problem statement was quite interesting because that not only judged my coding skills but also my mathematical skills. So i tried to solve it in two different ways –

Problem Statement
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44

As 1 = 14 is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19316.

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

Solution –

I first thought of getting the set of numbers (which meet the problem’s criteria) that are to be added, and then add them together to verify that the set is correct and complete.

Secondly, make a list of constraints which put restriction on the solution set. This problem excludes the value 1 from consideration. In fact, by intuitive extension, it is excluding all single digit values (numbers < 10) as they cannot form a sum of digits. This is a clue that our search range starts from at least 10.Now we have to think on the end range that’s the maximum limit till which our code should search. After just a moment of thought it becomes clear that the number of digits for the sum must have the same number of digits as a value.
Look at the table below to get the maximum limit.

Digits Maximum n Limit = 95 x n Comments
9 999,999,999 531,441 they need to have the same no. of digits
8 99,999,999 472,392 nope, still too many digits of n .
7 9,999,999 413,343 not quite there
6 999,999 354,294 a valid search limit

So we got the maximum limit as 354,294 . Now let’s write the code.

Python Code –

TotalSum = 0    
Value = []                             #values to be added

#Range we got and then comparing the values according to criteria
for i in range(10, 354294): 
    Sum = 0                       #This sum is for getting one single value 
    for x in str(i):
        Sum += int(x) ** 5        #checking for main condition with power 5 
    if Sum == i:                  #If the sum matches with the value 
        Value.append(i)           #The value we are in search for 

# We add those values stored in the list to get total Sum
for i in Value:
    TotalSum += i

print ("Values :" , Value)
print ("TotalSum :" , TotalSum)

Output ->

Values : [4150, 4151, 54748, 92727, 93084, 194979]
TotalSum : 443839

I also tried with other way by defining a function.

Python Code ->

def power_of_digits(n, exp = 5):
    Sum = 0
    while n > 0:
       Sum += (n % 10)**exp
       n //= 10
    return Sum

total = 0
for i in range(10, 10**6):
    if power_of_digits(i) == i:
        total += i
print(total)

Output ->

443839

Happy Coding! 🙂

Advertisements

Euler Problem no. 4 with Python

I Solved the 4th problem from the Euler’s problem set using python and found that it can be done in multiple ways. The problem is related to palindrome concept.

Problem Statement – 
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

I first approached the problem statement by thinking that how many maximum digits will a number have so 2 three digits will have max 6 digits number when multiplied and that can be easily achieved by first multiplying the biggest numbers so I took a reverse loop. And then checked the condition of being a palindrome number and displayed the greatest one after comparison .

Python Code ->

palindrome = 0 
# 2 variables to find the biggest palindrome
for a in range(999, 100, -1):       #First factor

#second factor starts from a so that one multiplication does not repeat.  
    for b in range(a, 100, -1): 
        number = a * b  
        if number > palindrome: 

#To check if number is a palindrome. 
            x = str(a * b)   
            if x == x[::-1]:  
                palindrome = a * b  
print(palindrome) 

Output ->

906609 

Trying More Euler’s Problem and the same code with C++. 🙂

Working on Python Dictionaries

As dictionary can store many key-value pairs in fact it can store millions of items. So to handle or work with all those items python lets us loop through the dictionary. There exists many ways to loop through all dictionary items by using the keys or the value

1) Looping in Dictionary through all items One of the simplest way (at least for me) is using a for loop. So before working with the key-value pairs let us make a dictionary to store the information of a student.

student_1 = {'name' : 'Samridhi' , 'nationality' : 'Indian' , 'Stream' : 'Electronics and Telecommunication' , 'age' : '19'}

Use of for Loop – To get a single item of a dictionary we can simply use the key value but to print the whole dictionary we use the for loop. We select the two variables names to hold the key and value of each item in dictionary. We can choose any name or any character as variable. The for loop stores each item in those variables. The method items() is used to return the list of items.

Example – To print the information of student_1 in an organized way.

for key, value in student_1.items():
 print("\nKey: " + key)
 print("Value: " + value)

Output ->

Key: age
Value: 19

Key: Stream
Value: Electronics and Telecommunication

Key: nationality
Value: Indian

key: name
value: Samridhi

This type of looping works well with millions of data and it also helps to see for choices of many people when the value remains same for many but key (name of a person) keeps on changing.

This way does not give all the key-value pairs in the same order as entered because looping does not take of that. So the items we get are in a unpredictable order. If you want a sorted dictionary to get the name of millions of students in an order makes it more readable so a sorted() function can be used with the for loop.

2) Looping in Dictionary through keys – The method keys() of using the keys of any item is used when you don’t have to work with all the values in the dictionary. Like if you just want to know the name of students participated in a certain competition and don’t want to know in which game they are participating we can just get the keys of dictionary (names of students).
Example: In a college fest there are 3 sports category but we want only those students who participate in any sport.

College_fest = {
'sam': 'basketball',
'vikky': 'cricket',
'rachi': 'football',
'yashu': 'basketball',
}

for name in College_fest.keys():
    print(name.title())

Output ->

Sam
Vikky
Rachi
Yashu

Looping in dictionary through keys() method is default behavior for looping in dictionary so for name in College_fest: is same as for name in College_fest.keys():

We can use the key() method to work with items explicitly and this can also be used in many ways like i want to check if a certain person is coming to an event or not.
Example – Check the list of students if Rashmi is present if not call her to play any game.

if 'rashmi' not in College_fest.keys() :
    print("Rashmi come to register your name for college fest!")

Output ->

Rashmi come to register your name for college fest!

3) Looping in Dictionary through Values – In the previous method we were more concerned with keys but here our main focus is on the values. The values() method is used to get the values stored in the dictionary. Like if you only want to know the name of sports that are in the college fest.
Example –  Get the name of all the games in the College_fest.

print("These are the games in the college fest -")
for game in College_fest.values():
    print(game.title())

Output ->

These are the games in the college fest -
Basketball
Cricket
Football
Basketball

But here the game basketball repeats itself  This method results in a repetitive list of values. This can be used in some other examples where you would require all the values but here we want a list without repetitions. In this case set comes to rescue. A set only stores unique values. When a list is wrapped around a set python identifies all the unique items and displays them as a set of unique items.
Example – To display a set of games in the college fest.

print("These are the games in the college fest -")
for game in set(College_fest.values()):
    print(game.title())

Output ->

These are the games in the college fest -
Basketball
Cricket
Football

So here is the list of games in the college fest.

Next time i will be writing on nesting in dictionary.
Till then Happy Looping Dictionary!

Musical Python

Today, sunday morning I wanted to listen to some soothing music, but the bad news was my internet connection was so poor that I could not even listen a song on YouTube without buffer. I really wished that I would have downloaded all the songs in my play-list before, from YouTube in mp3 format . So I thought of downloading the whole play-list today itself, but I did not want all the video files to get downloaded ( just wanted the mp3 version of all the videos) because that will burn my computer’s memory space. I also wanted to download the whole play-list in one go, so that i don’t have to select one song at a time.

So I thought of doing the same through python and wrote a very small code using the youtube-dl module of python. I was  happy after accomplishing a task through python that helps me. 🙂

You can go through my code here and use it for your play-list too just by changing the URL part (copying your own play-list url).

Python’s Dictionaries

Dictionaries allow us to bind almost limitless amount of real – world data more accurately. It allows you to connect pieces of related information. Like You want to store the information of all the students in a class, so you can make a dictionary representing one student and then store all his/her information as name, age, qualifications etc.

How to Create a Simple Dictionary – As dictionary is a collection of any type of data unlike other data types which have a common element for all its items. Dictionary has a key-value pair (collection). Each key has a associated value. Key makes it easy to retrieve the data.
A dictionary is made by wrapping all the items inside it by curly braces{}. Each item is separated by a comma inside the curly braces and each item represents a key-value pair. A key – value pair is represented as key : value, they are associated to each other so if you want to access value you should now the key. You can store as many items as you want in a dictionary.
Example – Take a student and enter his/her information in dictionary.

student_1 = {'name' : 'Samridhi' , 'nationality' : 'Indian' , 'Stream' : 'Electronics and Telecommunication'}

Here each item is separated by a comma and each key has a value. A key’s value can be anything a number, a list and even another dictionary. While values can repeat but keys are to be immutable and unique.There is also a built-in function dict() to create a dictionary.

Accessing a dictionary To access the value you need a key. In other data types we need some index number to access but in Dictionary we use keys. To get a value you have to mention the dictionary name and the key inside a square bracket or get() method can also be used.
Example – Accessing the name and nationality of student_1

print(student_1['name'])
print(student_1.get('nationality')

Output ->

Samridhi
Indian

The difference while using get() method is that it returns None instead of KeyError , if the key is not found.

Operations on Dictionaries –
1) Add items in Dictionary  – Dictionaries are mutable or dynamic so different changes can be made such as adding an item, changing the value or removing an item. To add a key-value pair, you have to give the name of the dictionary and a key in the square bracket is equal to a value.
Example – Adding the age as a parameter in the student_1 dictionary.

student_1['age'] = 19
print (student_1)

Output – >

{'name' : 'Samridhi' , 'nationality' : 'Indian' , 'Stream' : 'Electronics and Telecommunication' , 'age' : '19'}

If the key would have already present, value gets updated, else a new key: value pair is added to the dictionary. We can also start with an empty dictionary just defining a list with empty braces then start adding the key : value pairs (items).

2) Example of updating a key value in a dictionary –

student_1 = {'age': '19'}
print("The age is" + student_1['age'] + ".")
student_1['age'] = '20'
print("The age is now " + student_1['age'] + ".")

Output ->

The age is 19.
The age is now 20.

Providing the predefined key updates the value of the key.

3) Removing an item from the dictionary – When you think a certain item of information is not required you can simply delete the key:value pair by using the del statement. To delete a key you have to give the dictionary name and the key in the square bracket.
Example – Deleting the Nationality information of student_1

del student_1['nationality']
print(student_1)

Output ->

{'name' : 'Samridhi' , 'Stream' : 'Electronics and Telecommunication' , 'age' : '19'}

The item once deleted by using the del statement can not be retrieved, It is deleted permanently. To store the items but remove from the dictionary pop() method can be used by giving a key value. popitem() method can be used to remove the first key that is stored and clear() method to remove the whole dictionary. del statement can also be used to permanently delete a dictionary.

I will write more about dictionary about looping, storing similar items and how to work on dictionaries in my next blog! 🙂