Using map and filter/reduce to count how many times things come up in a sequence (python)
Question
I need to make a list of 50 random colours, then count how many times each colour has come up in that sequence. the only way i have found to do this is as shown below:
colours = [ "Red", "Blue", "Green", "Yellow", "Purple", "Orange", "White", "Black" ]
numbers = map(lambda x : random.randint(0,7), range(50))
randomcolours = map(lambda i: colours[i], numbers)
print randomcolours
x=collections.Counter(randomcolours)
print x
but i need to do it so i use map and filter or reduce.. i can't work out how to do it this way ?
Solution
random_colors = [random.choice(colors) for x in range(50)]
#because python's lambda is crappy, an extra local/global function must be defined
def count_color(di, color):
di.setdefault(color, 0)
di[color] = di[color]+1
return di
result = reduce(count_color, random_colors, {})
#The result is what you want
OTHER TIPS
You can use random.choice()
to populate your random_colors
list:
random_colors = [random.choice(colors) for x in range(50)]
And then one way to count all the occurances using map()
and filter()
can be:
c = dict(map(lambda to_filter: (to_filter, len(filter(lambda x: to_filter == x, random_colors))), colors))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow