Python Lecture 13-Dictionary
Python Lecture 13-Dictionary
efficiency of algorithms
B: Dictionary
Prime Numbers:
• Array of [2..n]
• Initialise:
– All numbers UNCROSSED
– x=2
• WHILE (x <= n)
– Proceed to next uncrossed number x. This is a
PRIME
– CROSS all multiples of x
Algorithm
Seive of Eratosthenes
def sieve(n):
save = [True] * (n+1)
save[0]=save[1]=False
i=2
n = int(input('Give n:'))
while (i*i <= n):
primes=sieve(n)
if (save[i]):
for i in range(n+1):
k = i*i
if primes[i]:
while (k<=n):
print(i)
save[k] = False
k += i
i += 1 driver program
return save
function sieve
Algorithm
Seive of Eratosthenes
• Time complexity
0 n=1
fib (n) = 1 n=2
fib (n-1) + fib (n-2) n > 2
Recursive Algorithm
fib (6)
fib (3) fib (2) fib (2) fib (1) fib (2) fib (1)
fib (6)
fib (3) fib (2) fib (2) fib (1) fib (2) fib (1)
Complexity O(2n)
Courtesy Prof PR Panda CSE Department IIT Dehi
Fibonacci Numbers (Modified)
• Based on memorization
• Save result when first computed
• Implement using an array (list)
Fibonacci Numbers (Modified)
Fibonacci Numbers (Modified)
Complexity O(n)
Fibonacci Numbers (Modified)
• fib(34): 3524578
– For the naïve recursive program the number
of calls is 11405773
– For the modified program the number of calls
is 65
Dictionary
Motivation
• Consider that one wants to associate
name (id) with grades of students.
• Can obtain through two separate lists
– names: [‘Mukesh’, ‘Sham’, ‘Arpita’, ‘Neha’]
– grades:[‘A-’,’B’,’A’,’C’]
• Separate list of same length for each item
• Associated information stored across lists
at same index
• Retrieval and manipulation is not easy
Motivation
• Consider that one wants to associate
name (id) with grades of students.
• Can obtain through two separate lists
– names: [‘Mukesh’, ‘Sham’, ‘Arpita’, ‘Neha’]
– grades:[‘A-’,’B’,’A’,’C’]
• Separate list of same length for each item
• Associated information stored across lists
at same index
• Retrieval and manipulation is not easy
Dictionary
• Natural data structure to store pairs of
data.
– key (custom index by label)
– value
Dictionary
• Lookup:
– similar to indexing into list
– looks up the key and returns the value
associated with the key
– if key is not found returns error
– print(grades[‘Sham’]) à B
– print(grades[‘Amit’]) à Error
Dictionary
• Other operations:
– add an entry:
• grades[‘Ankit’]=‘B-’
{'Mukesh': 'A-', 'Sham': 'B', 'Arpita': 'A', 'Neha': 'C', 'Ankit': 'B-'}