Exercises day 2¶
Control Structures¶
Make the following tests green:
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 | def simple_generator():
"""
Also yield 'cow' and 'mouse'.
"""
yield 'horse'
def test_simple_generator():
assert list(simple_generator()) == ['horse', 'cow', 'mouse']
# ------------------------------------------------------------------------
def simple_range(limit):
"""Yield numbers from 0 up to but not including limit.
You can use a normal while loop."""
pass
def test_simple_range():
assert list(simple_range(0)) == []
assert list(simple_range(3)) == [0, 1, 2]
# ------------------------------------------------------------------------
def word_lengths(words):
"""
Return a list of the length of each word.
(Use len(word).)
"""
pass
def test_word_lengths():
words = ['lorem', 'ipsum', 'python', 'sit', 'amet']
lengths = [5, 5, 6, 3, 4]
assert word_lengths(words) == lengths
# ------------------------------------------------------------------------
def simple_filter(f, l):
"""
Implement a simple filter function.
Do not use the built-in filter().
"""
return None
def test_simple_filter():
def greater_than_ten(n):
return n > 10
assert simple_filter(greater_than_ten, [1, 20, 5, 13, 7, 25]) == [20, 13, 25]
# ------------------------------------------------------------------------
def simple_map(f, l):
"""
Implement a simple map function.
Do not use the built-in map().
"""
return None
def test_simple_map():
def square_me(x):
return x*x
assert simple_map(square_me, [1, 2, 3, 4, 5]) == [1, 4, 9, 16, 25]
|
Classes¶
Make the following tests green:
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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | def make_dog_class():
"""
Make a class `Dog` that satisfies the following conditions:
* a dog has an attribute `happiness` which is initially set to 100, and
which is decremented by 1 when time advances.
* when a dog meets another dog, both dogs' happiness is reset to 100.
* when a dog meets a fish, the dog feeds and the fish dies.
* Note: "when a dog meets a fish" need not have the same effect as "when
a fish meets a dog" - but extra kudos to you if you can make it so.
"""
# The classes Pet and Fish are taken from the talk, with the addition of
# '_advance_time_individual' in Pet.
class Pet:
population = set()
def __init__(self, name):
self.name = name
self.hunger = 0
self.age = 0
self.pets_met = set()
self.__class__.population.add(self)
def die(self):
print("{} dies :(".format(self.name))
self.__class__.population.remove(self)
def is_alive(self):
return self in self.__class__.population
@classmethod
def advance_time(cls):
for pet in cls.population:
pet._advance_time_individual()
def _advance_time_individual(self):
# the leading _ in an attribute name is a convention that indicates
# to users of a class that "this is an attribute that is used
# internally, I probably shouldn't call it myself"
self.age += 1
self.hunger += 1
def feed(self):
self.hunger = 0
def meet(self, other_pet):
print("{} meets {}".format(self.name, other_pet.name))
self.pets_met.add(other_pet)
other_pet.pets_met.add(self)
def print_stats(self):
print("{o.name}, age {o.age}, hunger {o.hunger}, met {n} others".
format(o = self, n = len(self.pets_met)))
class Fish(Pet):
def __init__(self, name, size):
self.size = size
super().__init__(name)
def meet(self, other_fish):
super().meet(other_fish)
if not isinstance(other_fish, Fish):
return
if self.size > other_fish.size:
self.feed()
other_fish.die()
elif self.size < other_fish.size:
other_fish.feed()
self.die()
Dog = None # make Dog class here
return Pet, Fish, Dog
def test_dog_class():
Pet, Fish, Dog = make_dog_class()
assert type(Dog) == type
attila = Dog("Attila")
assert hasattr(attila, "happiness")
assert attila.happiness == 100
tamerlan = Dog("Tamerlan")
Pet.advance_time()
assert attila.happiness == tamerlan.happiness == 99
attila.meet(tamerlan)
assert attila.happiness == tamerlan.happiness == 100
assert attila in tamerlan.pets_met
assert tamerlan in attila.pets_met
steve = Fish("Steve", 1)
assert attila.hunger > 0
attila.meet(steve)
assert attila.hunger == 0
assert not steve.is_alive()
###############################################################################
def define_hungry():
"""
Copy your classes from the first exercise, and make the following happen:
* all pets have an `is_hungry()` method which returns True if the animal is
hungry, and False if not. In general, pets are considered to be hungry
when their hunger is > 50. Dogs, however, are considered to be hungry
when their hunger is > 10.
* there is a classmethod `Pet.get_hungry_pets()` which returns the set of
pets that are currently hungry.
"""
Pet = Fish = Dog = None
return Pet, Fish, Dog
def test_define_hungry():
Pet, Fish, Dog = define_hungry()
p = Pet("p")
f = Fish("f", 1)
d = Dog("d")
assert isinstance(Pet.get_hungry_pets(), set)
for x, h in [(p, 51), (f, 51), (d, 11)]:
assert len(Pet.get_hungry_pets()) == 0
assert not x.is_hungry()
x.hunger = h
assert x.is_hungry()
assert Pet.get_hungry_pets() == {x}
x.hunger = 0
|
Containers¶
We revisit the “character statistics” exercise from yesterday. Implement a solution using collections.Counter:
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 | def character_statistics(text):
"""
Reads text from file file_name, then lowercases the text, and then returns
a list of tuples (character, occurence) sorted by occurence with most
frequent appearing first.
You can use the isalpha() method to figure out whether the character is in
the alphabet.
Use collections.Counter for counting.
"""
return None
def test_character_statistics():
text = """
To be, or not to be: that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them? To die: to sleep;
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to, 'tis a consummation
Devoutly to be wish'd. To die, to sleep;
To sleep: perchance to dream: ay, there's the rub;
For in that sleep of death what dreams may come
When we have shuffled off this mortal coil,
Must give us pause: there's the respect
That makes calamity of so long life;
For who would bear the whips and scorns of time,
The oppressor's wrong, the proud man's contumely,
The pangs of despised love, the law's delay,
The insolence of office and the spurns
That patient merit of the unworthy takes,
When he himself might his quietus make
With a bare bodkin? who would fardels bear,
To grunt and sweat under a weary life,
But that the dread of something after death,
The undiscover'd country from whose bourn
No traveller returns, puzzzles the will
And makes us rather bear those ills we have
Than fly to others that we know not of?
Thus conscience does make cowards of us all;
And thus the native hue of resolution
Is sicklied o'er with the pale cast of thought,
And enterprises of great pith and moment
With this regard their currents turn awry,
And lose the name of action.--Soft you now!
The fair Ophelia! Nymph, in thy orisons
Be all my sins remember'd."""
assert character_statistics(text) == [('e', 146), ('t', 120), ('o', 99), ('s', 88), ('a', 87),
('h', 79), ('r', 71), ('n', 70), ('i', 57), ('l', 44),
('d', 43), ('u', 41), ('f', 36), ('m', 32), ('w', 29),
('p', 24), ('c', 23), ('y', 18), ('b', 17), ('g', 14),
('k', 10), ('v', 8), ('z', 3), ('q', 2)]
|