WebMaps with Python

After few months of busy schedule in college, Today I got the time to sit back and play with python applications. So I started learning WebMaps with python and folium.

As WebMaps the name only says that its the demonstration of Maps using browser. They can not be made using the default functions of Python because for the browser application we need CSS, HTML and JavaScript. So we need to convert the python code into the HTML code. Folium, a third party library does the same.

We need to pip install folium, after that we import it in the project. How folium works is – Everything spins around a map object, So we create a map object and store it in a variable.

import folium
map = folium.Map

Here folium.Map is the class that creates the object “map”. You can do dir (folium) to see different functions and you will find Map there. Then we can do help (folium.Map) to get the parameters and what we can give in that class.

Screenshot from 2017-12-10 22-29-19Screenshot from 2017-12-10 22-32-41

In the parameters we see the Location attribute to specify the coordinates on the world Map.Width- which means you can specify the width of map to be displayed on browser window, otherwise 100% by default means it uses full browser window to display.Tiles is background of map and so on.

So We can give the location attribute and see the location. In the location attribute the coordinates are given as [latitude, longitude].

import folium
map = folium.Map([-90 , 50])

Now we have a map object in python code but it is not converted to HTML. So we point the map object and use save method to save it in the html form, creating a new html file. Map will be created in HTML format, So html is containing all the elements that render on the browser.

import folium
map = folium.Map([-50 , 50])

So I got a Map1.html file having the map of my latitude and longitude mentioned and as it is interactive mapping we can zoom in and out to see more details. Zoom parameter can also be added as (zoom_start = 6) and see changes with different zoom factors.



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

Output ->


Happy Coding! 🙂

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  

Output ->


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

Back to Coding Life!

After all this long time I returned back to my hostel (after a lot more traveling and sad days). Everything seems stable now and I wish this remains for a longer time. So today as I returned back there were many things and many tasks to be completed – the internship work (mainly), I missed the dgplug sessions 😦 (reading the logs), Assignments and College.

So Completed with few things now and enjoyed the whole day with my laptop (after 7 days long holiday). First I did the tasks of the internship work (still left with much more). Read the previous 4 logs which i missed (dgplug). There was a session in dgplug where warthog9 was there for the guest session. He was the one who gave us the battle bunnies in the PyCon Pune 2017 and i also wanted to ask him few things about the bunnies but hard luck missed the chance! But the session was great i read the logs and got to learn many things about hardware. 

I think I will take one more day to return to the normal schedule where i can write atleast two codes a day and learn things. Still I tried to complete most of the things (satisfied by myself 😛 ).

Euler Prolem no. 2

I solved the second question from the euler’s problem set with python first then i tried to do the same with c++ and I realized that it just does the same thing and same logic to be applied just increasing number of lines to code in C++.

Problem Statement – By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

So I will start with how I first thought of writing a precise and simple code. As the last digit in the Fibonacci series is the sum of all the prior numbers so if we minus all the odd values from last digit that is 4 million, we will get sum of all even numbers. But i went with searching for all the even numbers one by one till 4 million and adding them.

Python Code ->

sum = 0               # Assign variable sum as 0
a, b = 0, 1                # Taking a and b as values in Fibonacci series
while b < 4000000:         # Last value should be 4 million
    if b % 2 == 0:         # Checking if even
        sum += b           # Adding up all even values
    a, b = b, a + b        # swapping first value with second
print(sum)                 # print the sum 

Output ->


C++ Code  ->

using namespace std;
int main()
	int sum = 0;
	//3 variables to create the Fibonacci sequence from 0 to 4000000
	int a = 0;
	int b = 1;
	int c = 0;
	while (b <= 4000000)
		c = a + b;
		if (b % 2 == 0)      //check for even number
			total += b;
		a = b;
		b = c;
	cout << sum <<endl;
	return 0;

Output ->


Practicing more Euler’s problem.

Emacs Lisp

In yesterday’s dgplug session, we were taught the Emacs Lisp programming, something very new for me which I had never done before. I liked the way the code is written because of its simplicity and normal English language but the way in which parenthesis are put is little confusing. That can be actually done by practicing writing code in Emacs Lisp. I was given a link to a video in the session by the mentor which i found really helping. I summarized all the codes with comments we learned in the session. You can have a look for them here .

After the session we also got some work to do – We have to select a problem from the Project Euler  and implement the solution in Emacs Lisp. So I selected the very first problem that is –

Find the sum of all the multiples of 3 or 5 below 1000.

I first wrote the code in python –

sum = 0                           #assigned sum variable as 0
for i in range(0, 1000):          #used range function to iterate from 0,1000 in the for loop
if(i % 3 == 0) or (i % 5 == 0):   #checked the condition
sum += i                          #if true then add with sum 
print (sum)                       #print total sum

Output ->


I tried to proceed in the same way for Emacs Lisp programming and i got the output in two ways once defining a function and one without function.

1) Defining the function sum

(defun sum (list)
  (apply '+ (mapcar
	     '(lambda (x) (if (or (eql (% x 3) 0) (eql (% x 5) 0))
			      x 0) )
	     list) ))
(sum (number-sequence 1 999) ) 

Output ->

 233168 (#o707320, #x38ed0, ? ) 

In the first line I defined the function sum with parameter list then I wrote a condition to check and add all the numbers satisfying the condition to give the total. To give the range I used the number-sequence function.

2) Without using function and using loop (do)

 (let ((sum 0))
  (cl-loop for x from 1 to 999
	   do (if (or (zerop(mod x 3 )) (zerop(mod x 5 )))
		  (setq sum (+ x sum))))



Used the same logic but mentioned the range in the loop which is more problem statement oriented result.

I really liked the Euler’s problem statements will try to practice more from them each day.

PyLadies Pune Workshop

This Weekend was an awesome one, I got the chance this Saturday to take a Workshop on “Python Basics 101” where I and one of my friend taught many girls Python Basics.

Before giving the session I was so tensed because First Anwesha (Organizer of Pyladies Pune) and Kushal (CPython Core Developer) were going to come as guests so that was a big support for us but because of certain health issues they were not able to come. So we were having the thought of postponing the workshop but Anwesha and Kushal gave us confidence to take the whole seminar by ourselves. That gave us a real responsibility to handle the whole session, and we were having the aim of teaching everything we know. We made the Presentation with all the content and examples the whole night and practiced once in front of our own friends a night before and then we were ready to rock the workshop.

The next day, we saw students really came to attend the workshop (we were expecting less students) So there came our responsibility to make the workshop worth. And hopefully we did that, Everyone was satisfied and we checked everyone’s coding skills by giving them questions in last 1 hour of the session and there was the aura of competition at the last( because we were having 2 chocolates by chance and we gave that who solved first). Many students came to ask more about PyLadies Pune and i was so happy to tell them as I can surely say that PyLadies totally turned me into a different person (good according to me). This opportunity taught me many things, Learn by Teaching and handle things. All Thanks to my very good step of joining PyLadies Pune Group.

You all can look at the Presentation and stuff i taught here and tell me changes so that i can learn and improve.



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():

Output ->


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():

Output ->

These are the games in the college fest -

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()):

Output ->

These are the games in the college fest -

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


Output ->


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']

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! 🙂