Using reduce together with map
# The total number of characters in a list of words
def demoReduce(yesOrNo):
if yesOrNo == 1:
return totalNumCharactersUsingReduce(cheeses)
else:
return totalNumCharactersUsingLoop(cheeses)
def totalNumCharactersUsingLoop(wordList):
totalNumOfChars = 0
for word in wordList:
totalNumOfChars += len(word)
return totalNumOfChars
# We go through the list of word lengths (compare demoMap)
def totalNumCharactersUsingReduce(list):
return reduce(add, map(len, list))
def add(a, b):
return a+b
Link to this Page