Skip to content

Commit 7012bc5

Browse files
committed
Day 16-18. Learned about list comprehension and generators.
1 parent 9a4fc2e commit 7012bc5

File tree

2 files changed

+61
-2
lines changed

2 files changed

+61
-2
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import random
2+
3+
def gen_pairs(the_names, number = 10):
4+
for i in range(0, number):
5+
name1 = random.choice(the_names).split()[0]
6+
name2 = random.choice(the_names).split()[0]
7+
while name2 == name1:
8+
name2 = random.choice(the_names).split()[0]
9+
yield f"{name1} teams up with {name2}"
10+
11+
def gen_pairs_theirs():
12+
first_name2 = [name.split()[0].title() for name in NAMES]
13+
while True:
14+
first, second = None, None
15+
while first == second:
16+
first, second = random.sample(first_name2, 2)
17+
18+
yield f'{first} teams up with {second}'
19+
20+
21+
22+
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos', \
23+
'julian sequeira', 'sandra bullock', 'keanu reeves', \
24+
'julbob pybites', 'bob belderbos', 'julian sequeira', \
25+
'al pacino', 'brad pitt', 'matt damon', 'brad pitt']
26+
27+
print(NAMES)
28+
29+
capital_names = [name.title() for name in NAMES]
30+
31+
print(capital_names)
32+
33+
swapped_names = [temp.split()[1] + " " + temp.split()[0] for temp in NAMES]
34+
35+
print(swapped_names)
36+
37+
def reverse_first_last_names(name):
38+
first, last = name.split()
39+
return f'{last} {first}'
40+
41+
42+
swapped_names2 = [reverse_first_last_names(name) for name in NAMES]
43+
44+
print(swapped_names2)
45+
46+
pairs = gen_pairs(capital_names)
47+
for _ in range(10):
48+
print(next(pairs))
49+
50+
51+
pairs2 = gen_pairs_theirs()
52+
for _ in range(10):
53+
print(next(pairs2))
54+
55+
import itertools
56+
57+
itertools.islice(pairs2, 10)
58+
list(itertools.islice(pairs2, 10))
59+

days/16-18-listcomprehensions-generators/list-comprehensions-generators.ipynb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -503,13 +503,13 @@
503503
{
504504
"ename": "StopIteration",
505505
"evalue": "",
506-
"output_type": "error",
507506
"traceback": [
508507
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
509508
"\u001b[0;31mStopIteration\u001b[0m Traceback (most recent call last)",
510509
"\u001b[0;32m<ipython-input-21-63d934b06ce9>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# no more values to generate\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mgen\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
511510
"\u001b[0;31mStopIteration\u001b[0m: "
512-
]
511+
],
512+
"output_type": "error"
513513
}
514514
],
515515
"source": [

0 commit comments

Comments
 (0)