Write this accumuator in a functional style
Gregory Ewing
greg.ewing at canterbury.ac.nz
Tue Jul 11 02:36:48 EDT 2017
Steven D'Aprano wrote:
> Help me humour my colleague.
class Parrot:
def __init__(self, color, species, status):
self.color = color
self.species = species
self.status = status
def __repr__(self):
return "%s/%s/%s" % (self.species, self.color, self.status)
def parrot_generator():
yield Parrot(color='blue', species='Norwegian',
status='tired and shagged out')
yield Parrot(color='green', species='Portugese', status='perky')
yield Parrot(color='red', species='Hawaiian', status='laid back')
yield Parrot(color='blue', species='Norwegian', status='dead')
yield Parrot(color='green', species='Italian', status='excited')
yield Parrot(color='blue', species='French', status='tres bon')
def parrots_of_color(parrots, color):
return [p for p in parrots if p.color == color]
def accumulated_parrots(parrot_source):
parrots = list(parrot_source)
return {color: parrots_of_color(parrots, color)
for color in set(p.color for p in parrots)}
print(accumulated_parrots(parrot_generator()))
More information about the Python-list
mailing list