osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Write this accumuator in a functional style


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()))