Skip to content

Commit 36c1050

Browse files
author
gsp
committed
List comprehension exercise
1 parent ad6187c commit 36c1050

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
Can you write a simple list comprehension to convert these names to title case (brad pitt -> Brad Pitt). Or reverse the first and last name?
3+
Then use this same list and make a little generator, for example to randomly return a pair of names, try to make this work:
4+
5+
pairs = gen_pairs()
6+
for _ in range(10):
7+
next(pairs)
8+
Should print (values might change as random):
9+
10+
Arnold teams up with Brad
11+
Alec teams up with Julian
12+
Have fun!
13+
14+
"""
15+
16+
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',
17+
'julian sequeira', 'sandra bullock', 'keanu reeves',
18+
'julbob pybites', 'bob belderbos', 'julian sequeira',
19+
'al pacino', 'brad pitt', 'matt damon', 'brad pitt']
20+
21+
# convert to title case
22+
convert_to_title_case = [actor.title() for actor in NAMES]
23+
print(convert_to_title_case)
24+
25+
# reverse first and last names
26+
27+
reverse_first_and_lastnames = [' '.join([actor.split(' ')[1], actor.split(' ')[0]]) for actor in NAMES]
28+
print(reverse_first_and_lastnames)
29+
30+
# Random team up
31+
import random
32+
33+
34+
def gen_pairs(some_list):
35+
name_one = 'start'
36+
name_two = 'start'
37+
while name_one == name_two:
38+
name_one = random.choice(some_list).split(' ')[0]
39+
name_two = random.choice(some_list).split(' ')[0]
40+
yield f'{name_one} teams up with {name_two}'
41+
42+
43+
for _ in range(len(convert_to_title_case)):
44+
team = next(gen_pairs(convert_to_title_case))
45+
print(team)

0 commit comments

Comments
 (0)