2-data-structures-discussion.md 18 KB
Newer Older
goekce's avatar
many:    
goekce committed
1
% Data structures discussion
goekce's avatar
typo    
goekce committed
2
3
% Gökçe Aydos

goekce's avatar
goekce committed
4
5
6
7
8
9
10
11
12
13
14

# Review Python basics

##
<!-- interactive interpreter, autocompletion -->
you are working on the interactive interpreter and have a string called `name`. You are trying to remember a method you used before, but cannot remember its exact name. What could help? 

A) `name.<F1>`
A) `name?`
A) `name.<TAB>`
A) `name.<SPACE>`
goekce's avatar
typos    
goekce committed
15
A) I don't know
goekce's avatar
goekce committed
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


<!-- interactive interpreter, getting more info etc -->
##
`name` is a string. You type `name.<TAB>` and see multiple methods available. How can you get information about which arguments a method has?

A) `name.method<F1>`
A) `name.method<TAB>`
A) `name.method?`
A) `help(method)`
A) I don't know

. . .

- `help(name.method)` also works
- also try
  - `str.*find*?`
  - `*Warning?`


<!-- modules, running vs importing -->
##
`efficient_words.py`:
```py
...
def is_efficient(word):
	...
def main():
	...
if __name__ == '__main__':
	main()
```

How can we run `is_efficient()` in the interactive interpreter?

A) `python efficient_words.py; is_efficient('ball')`
A) `./efficient_words.py; is_efficient('ball')`
A) `import efficient_words; is_efficient('ball')`
A) `from efficient_words import is_efficient; is_efficient('ball')`
A) I don't know


<!-- File I/O, advantage context manager -->
##
why the following should be preferred
```py
with open('words.txt') as f:
	...
```
over this?:
```py
goekce's avatar
typos    
goekce committed
67
f = open('words.txt')
goekce's avatar
goekce committed
68
69
70
71
72
73
74
75
76
77
...
```

A) the file will be closed independent of errors
A) we have to write less code
A) is tremendously faster
A) the second example can lead to syntax errors
A) I don't know


goekce's avatar
goekce committed
78
# lists
goekce's avatar
goekce committed
79
80
81
82
83
84
85
86
87
88
89
90
91
##
<!-- list, properties -->
which property does not belong to lists?

A) mutable
A) frozen
A) ordered
A) finite
A) I don't know


<!-- list, what does mutable mean? -->
##
goekce's avatar
goekce committed
92

goekce's avatar
goekce committed
93
94
95
96
97
98
99
```py
cheeses = ['gouda']
cheeses.append('paneer')

cheeses    # outputs ['gouda', 'paneer']
```

goekce's avatar
goekce committed
100
101
Which property of `list`s does the behavior above prove?

goekce's avatar
goekce committed
102
103
104
105
106
107
108
109
110
111
112
113
A) mutable
A) frozen
A) ordered
A) finite
A) I don't know


<!-- list, what does finite mean? -->
##
we mentioned that *lists are finite*. What does this mean?

A) we can create only a finite amount of lists in a Python program
goekce's avatar
typos    
goekce committed
114
A) a list has a finite amount of items
goekce's avatar
goekce committed
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
A) the variable names can take finite amount of characters
A) there are finite amount of list types in Python
A) I don't know
<!-- when do we have an infinite structure? generator functions (lazy evaluation) -->


<!-- list, add-on to the mutability question: what does mutable mean? -->
##
which property of strings does the inequality of `cheeses` and `favorites` prove?
```py
cheeses = 'gouda'
favorites = cheeses
cheeses += ' paneer'

cheeses    # outputs 'gouda paneer'
favorites  # outputs 'gouda'
```

A) immutable
A) frozen
A) ordered
A) finite
A) I don't know
<!-- strings are immutable, and Python creates a new object for `favorites` to point at-->


## 
<!-- functions vs methods -->
which is not a list method?

A) `len()`
A) `append()`
A) `count()`
A) `extend()`
A) I don't know


##
<!-- list, sorting using a key -->
sort the following list from the longest name to the shortest:

*Hint*: possible using a single line

```py
names = ['Cora', 'Su', 'Hüseyin']
```

. . .

```py
names.sort(key=len, reverse=True)
names  # ['Hüseyin', 'Cora', 'Su']
```


##
<!-- insert() -->
goekce's avatar
goekce committed
172
a number is missing in the following list with increasing numbers and you want to amend it. Which code does work?
goekce's avatar
goekce committed
173
174
175
176
```py
years=[2019, 2020, 2022]
```

goekce's avatar
goekce committed
177
178
179
180
A) `years += 2021`
A) `years += [2021]`
A) `years[2] += [2021]`
A) `years.insert(2, 2021)`
goekce's avatar
goekce committed
181
182
183
184
185
186
187
188
189
190
191
192
A) I don't know


##
<!-- in-place vs returning a new object -->
what is the output?
```py
names = ['Cora', 'Su', 'Hüseyin']
sorted(names, key=len)
names
```

goekce's avatar
goekce committed
193
194
195
196
A) `KeyError`
A) `['Su', 'Cora', 'Hüseyin']`
A) `['Cora', 'Su', 'Hüseyin']`
A) `['Hüseyin', 'Cora', 'Su']`
goekce's avatar
goekce committed
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
A) I don't know


##
<!-- reversing a list -->
Find three ways to reverse the following list:

*Hints*: `reversed()`, `reverse()`, `slicing`
```py
l=[1, 2, 3]
...
l  # outputs [3, 2, 1]
```

. . .

```py
list(reversed(l))
l[::-1]
l.reverse()
```


##
<!-- deleting, modifying lists -->
write code which corrects the quotation:
```py
kirk='Where yes monkey has gone sailing before!'
s=kirk.split()
s[...  # replace second and third words
...    # remove the second last word
...
goekce's avatar
goekce committed
229
```
goekce's avatar
goekce committed
230
231
232
233
234
235
236
237

. . .

[Quotation from Star Trek](https://en.wikipedia.org/wiki/Where_no_man_has_gone_before): 

> Space: the final frontier. These are the voyages of the starship Enterprise. Its five-year mission: to explore strange new worlds. To seek out new life and new civilizations. To boldly go where no man has gone before!

. . .
goekce's avatar
goekce committed
238

goekce's avatar
goekce committed
239
240
241
242
243
244
245
```py
s[1:3] = ['no', 'man']
del s[-2]  # or s.remove('sailing'), s.pop(-2)
' '.join(s)
```


goekce's avatar
goekce committed
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
##
<!-- shallow copy -->
```py
p1 = ['Helia', 1995]
p2 = ['Ram', 1993]
group1 = [p1, p2]
group2 = group1.copy()
group2[0].append('space')
group1, group2
```
A) ```py
([['Helia', 1995, 'space']],
 [['Helia', 1995, 'space'], ['Ram', 1993]])
```
A) ```py
([['Helia', 1995, 'space'], ['Ram', 1993]],
 [['Helia', 1995, 'space'], ['Ram', 1993]])
```
A) ```py
([['Helia', 1995], ['Ram', 1993]],
 [['Helia', 1995, 'space'], ['Ram', 1993]])
```
A) ```py
([['Helia', 1995], ['Ram', 1993]],
 ['space', ['Helia', 1995], ['Ram', 1993]])
```
A) I don't know

. . .

- this is called *shallow copy*. Also works: `group2 = group1[:]`


##
<!-- shallow copy only copies references -->
```py
p1 = ['Helia', 1995]
p2 = ['Ram', 1993]
group1 = [p1, p2]
group2 = group1.copy()
group2[0].append('space')
group1.pop()  # added compared to previous problem
group1, group2
```
A) ```py
([['Helia', 1995, 'space']],
 [['Helia', 1995, 'space'], ['Ram', 1993]])
```
A) ```py
([['Helia', 1995, 'space'], ['Ram', 1993]],
 [['Helia', 1995, 'space'], ['Ram', 1993]])
```
A) ```py
([['Helia', 1995], ['Ram', 1993]],
 [['Helia', 1995, 'space'], ['Ram', 1993]])
```
A) ```py
([['Helia', 1995], ['Ram', 1993]],
 ['space', ['Helia', 1995], ['Ram', 1993]])
```
A) I don't know

. . .

- alternative to shallow copy: [`copy.deepcopy()`](https://docs.python.org/3/library/copy.html?#copy.deepcopy)


##
<!-- deep copy digs deeper  -->
```py
from copy import deepcopy
p1 = ['Helia', 1995]
p2 = ['Ram', 1993]
group1 = [p1, p2]
group2 = deepcopy(group1)
group2[0].append('space')
group1, group2
# outputs:
([['Helia', 1995], ['Ram', 1993]],
 [['Helia', 1995, 'space'], ['Ram', 1993]])
```
goekce's avatar
goekce committed
327
328


goekce's avatar
goekce committed
329
330
# tuples

goekce's avatar
goekce committed
331
##
goekce's avatar
goekce committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
<!-- difference between tuples and lists -->
which is false?

A) lists cannot be altered but tuples can
A) both tuples and lists can store heterogeneous data (different datatypes)
A) packing and unpacking data is more convenient with tuples (we have to type less)
A) `enumerate()` returns a tuple
A) I don't know

. . .

- when we use `list`s as a collection, we tend to fill it with a single data type even `list`s support also heterogeneous data. The reason could be that we iterate over the collection and mostly apply similar operations on the items.

  tuples on the other hand contain usually heterogeneous data.
goekce's avatar
new qs    
goekce committed
346
347
348
349
350

contd...

## 2

goekce's avatar
goekce committed
351
352
353
354
355
- tuples are usually used for *packing* and *unpacking* data. Lists can also be used for this purpose, but tuples are more convenient: `a,b,c = x`
- if you need a collection as a key to a `dict`, you would need a hashable (and therefore immutable) data structure like `tuple` or `frozenset`

more info: [data structures tutorial - tuples and sequences](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences)

Gökçe Aydos's avatar
Gökçe Aydos committed
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
## 3

We said that lists can also be used for unpacking. Let us see some examples:

```py
x = [1, 2, 3]
print(x)
# outputs the list: `[1, 2, 3]`

print(*x)
# outputs print(x[0], x[1], x[2]): `1 2 3`
```

## 4

What about other containers?

```py
d = {1:'a', 2:'b', 3: 'c'}
x, y, z = d
print(x)  # outputs `1`
print(*d)  # outputs `1 2 3`

s = {1, 2, 3}
x, y, z = s
print(x)  # outputs `1`
print(*s)  # outputs `1 2 3`
```

Nice!
goekce's avatar
goekce committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400

##
<!-- editing does not work on tuples, tuples can be defined w/o parantheses -->
What is the output?
```py
s = 'Hello', 12
s[0] = 'Namaste'
s
```

A) `TypeError`
A) `{'Namaste'}`
A) `('Namaste')`
A) `['Namaste']`
A) I don't know
goekce's avatar
goekce committed
401
402
403
404


##
<!-- unpacking values -->
goekce's avatar
goekce committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
what is the output?
```py
m1 = 'BRAF', 'P15056', 673
m2 = 'AKT1', 'P31749', 207
# ...
gene, _, entrez_id = m1
f'{gene} has the Entrez id {entrez_id}.'
```

A) `BRAF has the Entrez id 673.`
A) `BRAF has the Entrez id P31749`
A) `'BRAF' has the Entrez id 'P31749'`
A) `SyntaxError`
A) I don't know
goekce's avatar
goekce committed
419
420
421
422


##
<!-- swapping values in one step -->
goekce's avatar
goekce committed
423
424
425
426
427
428
429
430
```py
a = 0; b = 1
b = a; a = b
a, b  # outputs: (0, 0)
```
What is the output?
```py
a = 0; b = 1
goekce's avatar
goekce committed
431
a, b = b, a
goekce's avatar
goekce committed
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
a, b
```

A) `SyntaxError`
A) `(1, 0)`
A) `(0, 1)`
A) `(b, a)`
A) I don't know


##
<!-- using tuples as a key in dict -->
you want to create a mapping between ingredients and the meal. Which meals are edible? All of them. But how many are not edible for Python?
```py
meals = dict()
```
goekce's avatar
goekce committed
448

goekce's avatar
goekce committed
449
450
451
452
453
454
455
456
457
458
- `meals['water',] = 'water'`
- `meals[['water', 'heat']] = 'cooked water'`
- `meals['rice', 'water', 'heat'] = 'cooked rice'`
- `meals[{'milk', 'bacteria'}] = 'yogurt'`

A) 1
A) 2
A) 3
A) 4
A) I don't know
goekce's avatar
goekce committed
459
460
461
462


##
<!-- unpacking tuples into functions, star operation -->
goekce's avatar
new qs    
goekce committed
463
464
465
466
467
468
469
470
471
```py
data = 'Elif', 'Sinatra', 1993

def db_add(forename, surname, birthyear):
	# appends the person to the database
	...
```
Which does not work?

goekce's avatar
typo    
goekce committed
472
A) `db_add(data[0], data[1], data[2])`
goekce's avatar
new qs    
goekce committed
473
474
475
476
477
A) `db_add(birthyear=data[2], forename=data[0], surname=data[1])`
A) `db_add(data)`
A) `db_add(*data)`
A) I don't know

goekce's avatar
goekce committed
478
479
480
481


##
<!-- `enumerate()` -->
goekce's avatar
new qs    
goekce committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
```py
l = [5, 3, 1, 2, 6, 4]
def bubble(numbers):
	# takes the first number (n = numbers[0])
	# swaps with its right neighbor if `n` greater
	# continues swapping n as long as it can

bubble(l)  # [3, 1, 2, 5, 6, 4]
```

. . .

explanation on next slide...


## 2

[Do not try to modify the list that you are looping on using an item](https://www.quora.com/Why-can’t-you-modify-lists-through-for-in-loops-in-Python), because the items will not be updated after starting the loop, e.g.:

```py
def bubble(numbers):
	for i, n in enumerate(numbers[:-1]):
		print(n, numbers[i+1], numbers[i:i+2])
		if n > numbers[i+1]:
			numbers[i:i+2] = numbers[i+1], n
		else:
			break
	return numbers
```

contd...


## 3

You see that the `n` does not get updated even we swap the items in the list. Correct solution is to use the item variable for the values in the original list, and store the first number in another variable.

```py
def bubble(numbers):
	first=numbers[0]
	for i, n in enumerate(numbers[:-1]):
		if i == 0:
			continue
		elif first > n:
			numbers[i-1], numbers[i] = n, first
		else:
			break
	return numbers
```
goekce's avatar
goekce committed
531
532
533


##
goekce's avatar
new qs    
goekce committed
534
<!-- mutable object in a tuple -->
goekce's avatar
goekce committed
535
536
537
538
539
540
541
542
543
544
545
546
547
```py
directors = ['Craig Foster']
d = 'The Great Dance', 2000, directors
directors += ['Demon Foster']
d[2]
```
What is the output?

A) `TypeError: 'tuple' object does not support item assignment`
A) `IndexError: 'tuple' object items cannot be altered`
A) `['Craig Foster']`
A) `['Craig Foster', 'Demon Foster']`
A) I don't know
goekce's avatar
goekce committed
548
549
550

. . .

goekce's avatar
goekce committed
551
The tuple stores the reference, which does not change even we alter the list.
goekce's avatar
goekce committed
552
553
554
555
556


# dictionaries
##
<!-- how do we declare dictionaries? -->
goekce's avatar
goekce committed
557
558
559
560
561
562
563
In which case `d` is not a dict?

A) `d = {'Botswana' => 'Africa'}`
A) `d = {'Karoha Langwane' : 'San'}`
A) `d = dict()`
A) `d = {}`
A) I don't know
goekce's avatar
goekce committed
564
565
566


##
goekce's avatar
goekce committed
567
568
569
570
571
572
573
574
575
<!-- key vs value -->
which is wrong?

```py
d = {'Mounika' : 'LSI',
     'Adem' : 'LSI',
     'Sriraam' : 'MCS'}
``` 

Gökçe Aydos's avatar
Gökçe Aydos committed
576
A) the forenames in `d` are the keys of `d`
goekce's avatar
goekce committed
577
578
579
580
581
582
583
A) every key in a dict is unique
A) values can be of every datatype
A) keys can be of every datatype
A) I don't know

. . .

Gökçe Aydos's avatar
Gökçe Aydos committed
584
585
586
Python generates a hash (a unique number) out of each key which is not allowed to change during the lifetime of a dict. Therefore keys must be immutable.

Why can we only use immutable items? Couldn't we create a hash out of a `list`?
goekce's avatar
goekce committed
587

Gökçe Aydos's avatar
Gökçe Aydos committed
588
589
590
It is possible but then we would have to calculate the hash everytime we use the list as a key. You would had to pay attention that the list never changes. A better way is to not allow it at all by using for example `tuple`s.

Practically Python does not allow this [by looking for a method called `__hash__` to see if an object can be used as a key](https://stackoverflow.com/a/25193267).
goekce's avatar
goekce committed
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607

##
<!-- similarity between dict and set -->
a dict stripped of its values corresponds to a:

A) list
B) set
C) tuple
D) defaultdict
A) I don't know

. . .

```py
d = {'a' : 'vowel, 'b' : 'consonant'}
set(d)  # outputs {'a', 'b'}
```
goekce's avatar
goekce committed
608
609
610


##
goekce's avatar
goekce committed
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
<!-- KeyError -->
```py
d = {'Kalahari desert' : ['springbok', 'vulture']}
d['Sahara desert'].append('desert fox')
d
```
What is the output?

A) `KeyError: 'Sahara desert'`
A) `IndexError: 'Sahara desert'`
A) ```py
{'Kalahari desert' : ['springbok', 'vulture'],
 'Sahara desert': ['desert fox']}
```
A) ```py
{['Kalahari desert', 'Sahara desert'] :
 ['springbok', 'vulture', 'desert fox']}
```
A) I don't know

. . .

goekce's avatar
goekce committed
633
<!-- avoiding keyerrors by using getting with default -->
goekce's avatar
goekce committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
How can we fix this?


## 2

- ```py
d['Sahara desert'] = []
d['Sahara desert'].append('desert fox')
```
- ```py
from collections import defaultdict
d = defaultdict(list)
# now every value will be automatically a list
d['Sahara desert'].append('desert fox')
```

which option do you find more convenient?

. . .

the first choice has more freedom. The values can have other datatypes than `list` compared to the second choice. The second choice makes sense if you already know that the dict will store `str`-`list` pairs. This approach could avoid wrong usage of the dict.
goekce's avatar
goekce committed
655
656
657
658


##
<!-- deleting elements -->
goekce's avatar
goekce committed
659
660
661
662
663
```py
character2house = {'Ron' : 'Gryffindor',
                   'Hermione' : 'Gryffindor',
                   'Draco' : 'Slytherin'}
for k, v in character2house.copy().items():
Gökçe Aydos's avatar
typo:    
Gökçe Aydos committed
664
	if v == 'Gryffindor':
goekce's avatar
goekce committed
665
666
667
668
669
670
		### YOUR CODE HERE
```
Which code deletes all characters which belong to the house Gryffindor?

A) `del v`
A) `del k`
Gökçe Aydos's avatar
Gökçe Aydos committed
671
672
A) `character2house.pop(k)`
A) `character2house.popitem()`
goekce's avatar
goekce committed
673
674
675
676
677
678
679
680
681
682
683
684
A) I don't know

. . .

- we have to copy the dict, otherwise we could get a `RuntimeError: dictionary changed size during iteration`

...


## 2

- `del` cannot know which key to delete if the dict's name is not given
Gökçe Aydos's avatar
clarify    
Gökçe Aydos committed
685
686
687
- `d.popitem()` returns the lastly added item and deletes it, so items with the keys `'Draco'` and `'Hermione'` will be removed instead of `'Ron'` and `'Hermione'`.
  - an *item* is a component of a collection. An item of a dict is a key-value pair.
  - note that `d.popitem(k, v)` does not exist. It would not make sense, because we can easily access items by their key
goekce's avatar
goekce committed
688
689
690
691


##
<!-- keys, values, items -->
Gökçe Aydos's avatar
Gökçe Aydos committed
692
`d` is a `dict`. Which iteration does not work?
goekce's avatar
goekce committed
693
694
695
696
697
698

A) `for k in d.keys()`
A) `for k, v in d`
A) `for v in d.values()`
A) `for k, v in d.items()`

Gökçe Aydos's avatar
Gökçe Aydos committed
699
700
<!-- TODO what if k,v are tuples in B) -->

goekce's avatar
goekce committed
701
702
703
. . .

-  `for k in d` iterates over the keys of `d`
goekce's avatar
goekce committed
704
705
706
707


##
<!-- d.copy() makes a *shallow* copy -->
goekce's avatar
goekce committed
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
```py
her = {'Lady Gaga' : ['pop'],
       'Mozart' : ['classic']}
mine = her.copy()
mine['Lady Gaga'].append('jazz')
her, mine
```
A) ```py
({'Lady Gaga': ['pop'], 'Mozart': ['classic']},
 {'Lady Gaga': ['pop', 'jazz'], 'Mozart': ['classic']})
```
A) ```py
({'Lady Gaga': ['pop', 'jazz'], 'Mozart': ['classic']},
 {'Lady Gaga': ['pop', 'jazz'], 'Mozart': ['classic']})
```
A) `TypeError`
A) ```py
({'Lady Gaga': ['pop'], 'Mozart': ['classic']},
 {'Lady Gaga': ['jazz'], 'Mozart': ['classic']})
```
A) I don't know
goekce's avatar
goekce committed
729
730


goekce's avatar
new qs    
goekce committed
731
732
##
<!-- double star operation -->
goekce's avatar
goekce committed
733
734
735
736
737
738
739
740
```py
def f(a, b, c):
	return a**b + c
d1 = 2, 5, 10
d2 = {'b': 5, 'c': 6, 'a': 10}
```
which line does not output 42?

goekce's avatar
typo    
goekce committed
741
742
743
744
A) `f(d1)`
A) `f(d1[0], d1[1], d1[2])`
A) `f(*d1)`
A) `f(**d2)`
goekce's avatar
goekce committed
745
746
A) I don't know

goekce's avatar
new qs    
goekce committed
747

goekce's avatar
goekce committed
748
# Sets
goekce's avatar
goekce committed
749

goekce's avatar
goekce committed
750
751
752
##
<!-- advantage: fast membership testing -->

goekce's avatar
goekce committed
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
which is not true?

A) a list can be converted to a set
A) a set can be converted to a list
A) an item can be found in roughly equal time in set and list, because sets are simply lists without duplicates
A) `set` has similar methods to the mathematical set operations, e.g., *intersection*
A) I don't know

. . .

- why are sets so fast? :racehorse:

## 2

- proof for fast membership testing

```py
l = [i for i in range(1_000_000)]
len(l)  # 1000000
s = set(l)
len(s)  # 1000000

%%timeit
0 in l
1000 in l
1_000_000 in l
# ~ 10 ms mean

%%timeit
0 in s
1000 in s
1_000_000 in s
# ~ 72 ns mean
```

goekce's avatar
goekce committed
788
789

##
goekce's avatar
goekce committed
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
<!-- set eliminates duplicates -->
The file `/usr/share/dict/catalan` contains words. Write code which

- converts the words to lowercase
- eliminates the duplicates
- stores the results as a collection of words to `words`
- writes them the file `/tmp/catalan_without_duplicates`:

```py
with open('/usr/share/dict/catalan') as f:
	### YOUR CODE HERE
```

. . .

```py
with open('/usr/share/dict/catalan') as f:
	words = {l.strip().lower() for l in f.readlines()}
```

- `set` eliminates duplicates
goekce's avatar
goekce committed
811
812
813


##
goekce's avatar
goekce committed
814
815
816
817
818
819
820
821
<!-- defining an empty set -->
which defines an empty set?

A) `{}`
A) `{pass,}`
A) `set()`
A) `()`
A) I don't know
goekce's avatar
goekce committed
822
823
824
825


##
<!-- converting a string to a set of letters -->
goekce's avatar
goekce committed
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
Print a word from `/usr/share/dict/usa` which contains all the English vowels:

```py
with open('/usr/share/dict/usa') as f:
	### YOUR CODE HERE
```

. . .

```py
vowels = set('aeiou')
with open('/usr/share/dict/usa') as f:
	while word := f.readline().strip().lower():
		letters = set(word)
		if letters >= vowels:
			print(word)
			break
# outputs: abstemious
```

:open_mouth:

> abstemious: eating and drinking in moderation

goekce's avatar
goekce committed
850
851
852
853


##
<!-- remove() vs discard() -->
goekce's avatar
goekce committed
854
855
856
857
858
859
860
861
862
863
864
865
You have a list of number sets and you want to remove the number `0` from all the sets. Which does work?
```py
number_sets = [ {5, 6, 1}, {2, 4, 0} ]
for s in number_sets:
	### YOUR CODE HERE
```

A) s.remove('0')
A) s.remove(0)
A) s.discard(0)
A) del s[0]
A) I don't know
goekce's avatar
goekce committed
866
867
868
869


##
<!-- how does Python differentiate dict and set definitions? -->
goekce's avatar
goekce committed
870
871
872
873
874
875
876
877
878
879
880
881
882
How many of the following is a set?

- `{}`
- `()`
- `set()`
- `{1: False}`
- `set([1,2,2])`

A) 1
A) 2
A) 3
A) 4
A) I don't know
goekce's avatar
goekce committed
883
884
885
886


##
<!--  | (union), - (difference), & (intersection) -->
Gökçe Aydos's avatar
Gökçe Aydos committed
887
888
889

Fill the gaps between `a` and `b`:

goekce's avatar
goekce committed
890
891
892
893
894
895
896
```py
a = {1, 2, 3}
b = {2, 3, 4}
a _ b = {1, 2, 3, 4}
a _ b = {1}
a _ b = {2, 3}
```
goekce's avatar
goekce committed
897

goekce's avatar
goekce committed
898
899
900
901
902
A) `|`, `-`, `&`
A) `+`, `-`, `&`
A) `-`, `&`, `+`
A) `U`, `-`, `&`
A) I don't know
goekce's avatar
goekce committed
903
904
905
906


##
<!-- a |= b-->
goekce's avatar
goekce committed
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
```py
a = {1, 2, 3}
b = {2, 3, 4}
c = {0, 5}
```
how many of the following creates a union of all sets and stores it in `a`?

- `a |= b|c`
- `a = a|b|c`
- `a = a.union(b,c)`
- `a += b+c`
- `a += a+b+c`

A) 1
A) 2
A) 3
A) 4
A) I don't know


##
Which datatypes do you know so far? :pen:

- **immutable**:
```








```
- **mutable**:
```








```