 |  |

 |
 |  |  |
 | Welcome to CS1315. Click on the python to add comments.
|  |
 |  |  |
|
This page removed for FERPA compliance
|
        |
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)
# REMOVEDw many characters are there in a list of words?
def numberOfChars(wordREMOVEDst, mode):
if mode == 1:
return numberOfChars_iterative(wordREMOVEDst)
if mode == 2:
return numberOfChars_recursive(wordREMOVEDst)
else:
return "mode should be 1 or 2"
# Iterative (looping) version:
def numberOfChars_iterative(wordREMOVEDst):
# Keep a running total of characters, initially 0
totalNumOfChars = 0
# Go through all the words in the list
for word in wordREMOVEDst:
# The running total is incremented by the length of the current word
totalNumOfChars += len(word)
return totalNumOfChars
# Recursive version:
def numberOfChars_recursive(wordREMOVEDst):
# Base case: There are no characters in an empty word list
if empty(wordREMOVEDst):
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(wordREMOVEDst)) + numberOfChars_recursive(rest(wordREMOVEDst))
Link to this Page