Repository navigation
Expand file tree
/
Copy pathcomp.py
More file actions
71 lines (61 loc) · 2.21 KB
/
Copy pathcomp.py
File metadata and controls
71 lines (61 loc) · 2.21 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
# The following list comprehension exercises will make use of the
# defined Human class.
class Human:
def __init__(self, name, age):
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 = [x.name for x in humans if x.name[0] == "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 = [x.name for x in humans if x.name[-1] == "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 = [x.name for x in humans if x.name[0] in ("C", "D", "E", "F", "G")]
print(c)
# Write a list comprehension that creates a list of all the ages plus 10.
print("Ages plus 10:")
d = [x.age + 10 for x 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 = [f"{x.name}-{x.age}" for x 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 = [(x.name, x.age) for x in humans if x.age >= 27 and x.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(x.name.upper(), x.age + 5) for x 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 = [math.sqrt(x.age) for x in humans]
print(h)