Repository navigation
Expand file tree
/
Copy pathcomp.py
More file actions
79 lines (69 loc) · 2.26 KB
/
Copy pathcomp.py
File metadata and controls
79 lines (69 loc) · 2.26 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
79
# 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 = []
a = [i.name for i in humans if (i.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 = []
b = [i.name for i in humans if (i.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 = []
c = [i.name for i in humans if (ord(i.name[0]) > 66 and ord(i.name[0])<72) ]
print(c)
# Write a list comprehension that creates a list of all the ages plus 10.
print("Ages plus 10:")
d = []
d = [i.age+10 for i 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 = []
e = [f"{i.name}-{i.age}" for i 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 = []
f=[(i.name, i.age) for i in humans if (i.age>26 and i.age<33)]
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 = []
g = [Human(i.name.upper(),i.age+5) for i 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 = []
h = [math.sqrt(i.age) for i in humans]
print(h)