Repository navigation
Expand file tree
/
Copy pathcomp.py
More file actions
78 lines (66 loc) · 2.5 KB
/
Copy pathcomp.py
File metadata and controls
78 lines (66 loc) · 2.5 KB
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
# The following list comprehension exercises will make use of the
# defined Human class.
from string import ascii_uppercase
from math import sqrt
class Human:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def __repr__(self):
return f"<Human: {self.name}, {self.age}>"
humans = [
Human("Alice", 29),
Human("Bob", 32),
Human("Charlie", 37),
Human("Daphne", 30),
Human("Eve", 26),
Human("Frank", 18),
Human("Glenn", 42),
Human("Harrison", 12),
Human("Igon", 41),
Human("David", 31),
]
# Write a list comprehension that creates a list of names of everyone
# whose name starts with 'D':
print("Starts with D:")
a = [human.name for human in humans if human.name.startswith('D')]
print(a)
# Write a list comprehension that creates a list of names of everyone
# whose name ends in "e".
print("Ends with e:")
b = [human.name for human in humans if human.name.endswith('e')]
print(b)
# Write a list comprehension that creates a list of names of everyone
# whose name starts with any letter between 'C' and 'G' inclusive.
print("Starts between C and G, inclusive:")
c_start = ascii_uppercase.index('C')
g_end = ascii_uppercase.index('G')
c = [human.name for human in humans if human.name[0] in ascii_uppercase[c_start: g_end+1]]
print(c)
# Write a list comprehension that creates a list of all the ages plus 10.
print("Ages plus 10:")
d = [human.age + 10 for human in humans]
print(d)
# Write a list comprehension that creates a list of strings which are the name
# joined to the age with a hyphen, for example "David-31", for all humans.
print("Name hyphen age:")
e = ['-'.join([human.name, str(human.age)]) for human in humans]
print(e)
# Write a list comprehension that creates a list of tuples containing name and
# age, for example ("David", 31), for everyone between the ages of 27 and 32,
# inclusive.
print("Names and ages between 27 and 32:")
f = [(human.name, human.age) for human in humans if human.age >= 27 and human.age <= 32]
print(f)
# Write a list comprehension that creates a list of new Humans like the old
# list, except with all the names uppercase and the ages with 5 added to them.
# The "humans" list should be unmodified.
print("All names uppercase:")
g = [Human(human.name.upper(), human.age+5) for human in humans]
print(g)
# Write a list comprehension that contains the square root of all the ages.
print("Square root of ages:")
import math
h = [sqrt(human.age) for human in humans]
print(h)
# completed sprint 2:34 7/16/2020