Finding the total number of characters in a list of words
# Some useful helper functions
def first(list):
return list[0]
def rest(list):
return list[1:]
def empty(list):
return (len(list) == 0)
# How many characters are there in a list of words?
def numberOfChars(wordList, mode):
if mode == 1:
return numberOfChars_iterative(wordList)
if mode == 2:
return numberOfChars_recursive(wordList)
else:
return "mode should be 1 or 2"
# Iterative (looping) version:
def numberOfChars_iterative(wordList):
# Keep a running total of characters, initially 0
totalNumOfChars = 0
# Go through all the words in the list
for word in wordList:
# The running total is incremented by the length of the current word
totalNumOfChars += len(word)
return totalNumOfChars
# Recursive version:
def numberOfChars_recursive(wordList):
# Base case: There are no characters in an empty word list
if empty(wordList):
return 0
# Recursive case: There are as many characters in a word list as there
# are in the first word, plus the number of characters in the rest of the words
else:
return len(first(wordList)) + numberOfChars_recursive(rest(wordList))
Link to this Page