Change Contents of the Bubble
Welcome to CS1315. Click on the python to add comments.

Looking for the book? They have it at the Engineer's Bookstore at 748 Marietta St NW. Here is there website: http://www.engrbookstore.com/ - Monica

Hotspots: Slides and CodeTA CornerComments?AnnouncementsFAQStatic Webspace
View this PageEdit this Page (locked)Uploads to this PageHistory of this PageHomeRecent ChangesSearchHelp Guide

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