-
Notifications
You must be signed in to change notification settings - Fork 20
/
dictionaries.py
executable file
·488 lines (331 loc) · 11 KB
/
dictionaries.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# -*- coding: utf-8 -*-
"""dictionaries.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1KQ1xeZw2LOh3fbwGlrKPyIa_-XnBarNn
# [Dictionaries](https://docs.python.org/3/library/stdtypes.html#dict)
Collections of `key`-`value` pairs.
"""
my_empty_dict = {} # alternative: my_empty_dict = dict()
print('dict: {}, type: {}'.format(my_empty_dict, type(my_empty_dict)))
"""## Initialization"""
mydiction= {}
type(mydiction)
dict11 = {'key1': 1.6, 'key2': 10, 'key3': 'John Doe'}
dict11
dict11['key4']=11
dict22 = dict(key1=1.6, key2=10, key3='John Doe')
dict22
mydiction = {0:'hello'}
mydiction
i=1
while(i<=5):
mydiction[i]=input("Enter the number")
i+=1
mymatrix=[[1,2,3],[4,5,6],[7,8,9]]
print(mymatrix)
mymatrix[1][0]
mymatrix[2][0]
mymatrix
"""#sparse matrix"""
mymatrix=[[0,2,0],[4,0,0],[0,0,9]]
mymatrix
mymatrix[0][1]
mymatrix[1][0]
mymatrix[2][2]
"""#Dict"""
mydiction = {(0,1):2,(2,0):4,(2,2):9}
mydiction
previous={0:0, 1:1}
if n not in previous:
previous[n]=value
previous
import time
def fibonacci(n):
if n not in previous:
#print("Inside this if")
val=fibonacci(n-1)+fibonacci(n-2)
previous[n]=val
return previous[n]
n=int(input("Enter the value of n:"))
start_time = time.time()
print("Fibonacci(", n,")= ", fibonacci(n))
print("Time:% ",(time.time() - start_time))
dict1 = {'value1': 1.6, 'value2': 10, 'name': 'John Doe'}
dict2 = dict(value1=1.6, value2=10, name='John Doe')
print(dict1)
print(dict2)
print('equal: {}'.format(dict1 == dict2))
print('length: {}'.format(len(dict2)))
"""## `dict.keys(), dict.values(), dict.items()`"""
print('keys: {}'.format(dict1.keys()))
print('values: {}'.format(dict1.values()))
print('items: {}'.format(dict1.items()))
print('keys: {}'.format(dict11.keys()))
print('values: {}'.format(dict11.values()))
print('items: {}'.format(dict11.items()))
"""## Accessing and setting values"""
my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 99
my_dict
my_dict['key1'] = 'new value' # overriding existing value
my_dict
my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 99
my_dict['key1'] = 'new value' # overriding existing value
print(my_dict)
print('value of key1: {}'.format(my_dict['key1']))
print(my_dict['key3'])
"""## Deleting"""
my_dict = {'key1': 'value1', 'key2': 99, 'keyX': 'valueX'}
del my_dict['keyX']
print(my_dict)
del my_dict['keyX']
key_to_delete = 'key1'
if key_to_delete in my_dict:
del my_dict[key_to_delete]
print(my_dict)
else:
print('{key} is not in {dictionary}'.format(key=key_to_delete, dictionary=my_dict))
my_dict = {'key1': 'value1', 'key2': 99, 'keyX': 'valueX'}
del my_dict['keyX']
print(my_dict)
# Usually better to make sure that the key exists (see also pop() and popitem())
key_to_delete = 'my_key'
if key_to_delete in my_dict:
del my_dict[key_to_delete]
else:
print('{key} is not in {dictionary}'.format(key=key_to_delete, dictionary=my_dict))
"""## Dictionaries are mutable"""
my_dict = {'ham': 'good', 'carrot': 'semi good'}
my_other_dict = my_dict
my_dict
my_other_dict
my_other_dict['carrot'] = 'super tasty'
my_dict = {'ham': 'good', 'carrot': 'semi good'}
my_other_dict = my_dict
my_other_dict['carrot'] = 'super tasty'
my_other_dict['sausage'] = 'best ever'
print('my_dict: {}\nother: {}'.format(my_dict, my_other_dict))
print('equal: {}'.format(my_dict == my_other_dict))
"""Create a new `dict` if you want to have a copy:"""
my_dict = {'ham': 'good', 'carrot': 'semi good'}
my_other_dict = dict(my_dict)
my_other_dict['beer'] = 'decent'
print('my_dict: {}\nother: {}'.format(my_dict, my_other_dict))
print('equal: {}'.format(my_dict == my_other_dict))
my_dict
my_other_dict
"""<a id='dict_get'></a>
## `dict.get()`
Returns `None` if `key` is not in `dict`. However, you can also specify `default` return value which will be returned if `key` is not present in the `dict`.
"""
my_dict = {'a': 1, 'b': 2, 'c': 3}
d = my_dict.get('a')
print('d: {}'.format(d))
d = my_dict.get('e', 'No Value')
print('d: {}'.format(d))
"""## `dict.pop()`"""
my_dict = dict(food='ham', drink='beer', sport='football')
print('dict before pops: {}'.format(my_dict))
food = my_dict.pop('food')
print('food: {}'.format(food))
print('dict after popping food: {}'.format(my_dict))
food_again = my_dict.pop('sport', 'default value for food')
print('food again: {}'.format(food_again))
print('dict after popping food again: {}'.format(my_dict))
food_again = my_dict.pop('drink', 'default value for food')
food_again
my_dict
my_dict = dict(food='ham', drink='beer', sport='football')
print('dict before pops: {}'.format(my_dict))
result = my_dict.popitem()
print('Result: {}'.format(result))
print('dict after popping items: {}'.format(my_dict))
"""## `dict.setdefault()`
Returns the `value` of `key` defined as first parameter. If the `key` is not present in the dict, adds `key` with default value (second parameter).
"""
my_dict = {'a': 1, 'b': 2, 'c': 3}
#a = my_dict.setdefault('a', 'my default value')
d = my_dict.setdefault('d', 'my default value')
print('a: {}\nd: {}\nmy_dict: {}'.format(a, d, my_dict))
"""## `dict.update()`
Merge two `dict`s
"""
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3}
dict1.update(dict2)
print(dict1)
# If they have same keys:
dict1.update({'c': 10})
print(dict1)
"""## The keys of a `dict` have to be immutable
Thus you can not use e.g. a `list` or a `dict` as key because they are mutable types
:
"""
bad_dict = {['my_list'], 'value'} # Raises TypeError
bad_dict = {'my_list', 'value'}
bad_dict
"""Values can be mutable"""
good_dict = {'my key': ['Python', 9.1, 3, 'cool']}
print(good_dict)
"""#Aliasing and copying"""
my_dict = dict(food='ham', drink='beer', sport='football')
print(my_dict)
my_dict_copy = my_dict
id(my_dict)
id(my_dict_copy)
my_dict_clone = my_dict.copy()
id(my_dict_clone)
"""#Sparse matrices"""
matrix = [ [0,0,0,1,0],
[0,0,0,0,0],
[0,2,0,0,0],
[0,0,0,0,0],
[0,0,0,3,0] ]
print(matrix)
matrix = {(0,3): 1, (2, 1): 2, (4, 3): 3}
print(matrix)
"""We only need three key-value pairs, one for each nonzero element of the matrix.
Each key is a tuple, and each value is an integer.
"""
matrix[4,2]
"""Instead of two integer indices, we use
one index, which is a tuple of integers.
If we specify an element that is zero, we get an error,
because there is no entry in the dictionary with that key:
"""
matrix[1,3]
"""The get method solves this problem: The first argument is the key; the second argument is the value get should
return if the key is not in the dictionary
"""
matrix.get((2,1), 0)
matrix.get((0,3), 0)
"""#Counting letters
<a id='dict_get'></a>
## `dict.get()`
Returns `None` if `key` is not in `dict`. However, you can also specify `default` return value which will be returned if `key` is not present in the `dict`.
"""
my_dict = {'a': 1, 'b': 2, 'c': 3}
d = my_dict.get('d')
print('d: {}'.format(d))
d = my_dict.get('c', 'value')
print('d: {}'.format(d))
letterCounts = {}
print(letterCounts)
for letter in "Mississippi":
#print(letter,letterCounts.get (letter, 0))
letterCounts[letter] = letterCounts.get (letter, 0) + 1
print(letterCounts)
letterCounts = {}
print(letterCounts)
for letter in "Malayalam":
print(letter,letterCounts.get (letter, 0))
letterCounts[letter] = letterCounts.get (letter, 0) + 1
print(letterCounts)
letterCounts
"""#Exercise"""
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
"""If you played around with the fibonacci function , you might
have noticed that the bigger the argument you provide, the longer the function
takes to run. Furthermore, the run time increases very quickly. On one of
our machines, fibonacci(20) finishes instantly, fibonacci(30) takes about a
second, and fibonacci(40) takes roughly forever
"""
fib(4)
import time
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
n=int(input("Enter the value of n:"))
start_time = time.time()
print("Fibonacci(", n,")= ", fib(n))
print("Time:% ",(time.time() - start_time))
i=0
n=int(input("Enter the limit : "))
print(f"{i}\n", end="")
i+=1
for x in range(2,n+1):
print(f"{i}\n",end="")
i+=i
"""Note the running time
[Call graph](https://github.com/sarithdm/python/blob/master/ITT%20205%20Problem%20Solving%20using%20Python/Module%202/cg.png)
A call graph shows a set function frames, with lines connecting each frame to
the frames of the functions it calls. At the top of the graph, fibonacci with
n=4 calls fibonacci with n=3 and n=2. In turn, fibonacci with n=3 calls
fibonacci with n=2 and n=1. And so on.
Count how many times fibonacci(0) and fibonacci(1) are called. This is an
inecient solution to the problem, and it gets far worse as the argument gets
bigger.
Good solution is to keep track of values that have already been computed by
storing them in a dictionary. A previously computed value that is stored for
later use is called a hint. Here is an implementation of fibonacci using hints
#Hints
"""
previous={0:0, 1:1}
def fibonacci(n):
if n not in previous:
val=fibonacci(n-1)+fibonacci(n-2)
previous[n]=val
return previous[n]
n=int(input("Enter the value of n:"))
print("Fibonacci(", n,")= ", fibonacci(n))
"""The dictionary named previous keeps track of the Fibonacci numbers we already
know. We start with only two pairs: 0 maps to 1; and 1 maps to 1.
Whenever fibonacci is called, it checks the dictionary to determine if it contains
the result. If it's there, the function can return immediately without
making any more recursive calls. If not, it has to compute the new value. The
new value is added to the dictionary before the function returns.
#Traversing dictionaries
"""
dict1 = {'a': 1.6, 'c': 10, 'b': 11}
for key in dict1:
print (key)
dict1.keys()
dict1.values()
dict1.items()
for (key,value) in dict1.items():
print (key,value)
keyslist=list(dict1.keys())
keyslist
keyslist.sort()
keyslist
for key in keyslist:
print (key,dict1[key])
"""#Reverse lookup
Given a dictionary d and a key k, it is easy to find the corresponding value v = d[k]. This operation is called a lookup.
"""
dict11 = {'key1': 1.6, 'key2': 10, 'key3': 'John Doe','key4':10}
value=dict11['key2']
value
value=dict11['key4']
value
"""But what if you have v and you want to find k? You have two problems: first, there might be more than one key that maps to the value v. Depending on the application, you might be able to pick one, or you might have to make a list that contains all of them. Second, there is no simple syntax to do a reverse lookup; you have to search.
Below function that takes a value and returns the first key that maps to that value:
"""
def reverse_lookup(d, v):
for k in d:
if d[k] == v:
return k
dict1 = {'a': 1.6, 'c': 10, 'b': 11}
reverse_lookup(dict1, 10)
reverse_lookup(dict1, 12)
"""#Student Ex"""
dict11 = {'key1': 1.6, 'key2': 10, 'key3': 'John Doe'}
for key in dict11:
print (key)
for key in dict11:
print(dict11[key])
dict11 = {'b': 1.6, 'c': 10, 'a': 'John Doe'}
"""#Adding Extra work"""
dict12 = {'b': 1.6, 'c': 10, 'a': 'John Doe'}
for keys,values in dict12.items():
print(keys,values)