MSBLOGS: June 2016

Pages

Thursday, June 9, 2016

Python script for creating fibonacci series till n number and converting list to dict.

Fibonacci series is the series in which the each number is sum of its previous 2 numbers.

for eg: 0 , 1, 2, 3 (2+1), 5(3+2), 8(5+3)......


Example of conversion of list to Dict and finding the Fibonacci number up to n..

Example.py


def fib(n1, n2):
        fibnum = n1+n2
        return fibnum

class test(object):

    n1 = 0
    n2 = 1
    fiblist = []
    count = 10
   
    while(count>0):
        fibnum = fib(n1, n2)
        n1 = n2
        n2 = fibnum
        fiblist.append(fibnum)
        count = count-1
    print fiblist
    lilen = len(fiblist)
    print "length of list is",lilen
    i=0
    key_val = []
    print "The ninth element in the list is ",fiblist[9]


    # Now to convert this list in dict and adding the serial number as key and value from the Fibonacci list generated above/
    # first we will create another list from 0 to length of fiblist and then will combine both lists.

    
    while i <lilen:
        key_val = key_val+[i]
        i = i+1
        #print key_val
    print "The list items which will be used as key of dict items ",key_val

    listtodict = zip(key_val, fiblist)


    print "The dict created using fiblist and key_val is ", listtodict
   
    print "the value of 9th key in the dict is", listtodict[9]
_________________________________________________________



The output of the program is : 

(On running this script by typing filename.py on cmd prompt or eclipse (python interpreter)


[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
length of list is 10
The ninth element in the list is  89
The list items which will be used as key of dict items  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The dict created using fiblist and key_val is  [(0, 1), (1, 2), (2, 3), (3, 5), (4, 8), (5, 13), (6, 21), (7, 34), (8, 55), (9, 89)]
the value of 9th key in the dict is (9, 89)
 

________________________________________________________