# File: recurPractice.py # Author: Dr. Gibson # Date: 4/19/2017 # Section: N/A # E-mail: k.gibson@umbc.edu # Description: # This file contains python code that recursively implements # a "valid grade getter" and has multiple implementations of # a recursive "list summer" function # recGetGrade() prompts the user for a grade between 0 and 100 # Input: none; (0 and 100 are default, not passed in) # Output: grade; an integer between 0 and 100, inclusive def recGetGrade(): grade = int(input("What is your grade? ")) # BASE CASE: valid grade if grade >= 0 and grade <= 100: return grade # RECURSIVE CASE: invalid grade else: print("That's not valid; must be between 0 and 100, inclusive.") # RECURSIVE CALL (with return, since a value is being returned) return recGetGrade() # recSumList1() sums a list by adding the first element to the rest # of the list recursively # Input: currList; a list of integers # Output: total of the list's contents def recSumList1(currList): # BASE CASE: list is empty, nothing more to sum together if len(currList) == 0: return 0 # RECURSIVE CASE: list is not empty, keep going else: # helps trace what's going on, but not necessary print("Adding", currList[0], "to", currList[1:] ) # RECURSIVE CALL: add first element to sum of rest of list return currList[0] + recSumList1( currList[ 1: ] ) # recSumList2() sums a list by keeping track of what index # we're at when adding the entire list together # Input: theList; a list of integers # currIndex; index of contents to be added in next # Output: total of the list's contents def recSumList2(theList, currIndex): # BASE CASE: reached the end of the list, stop adding if currIndex == len(theList): return 0 # RECURSIVE CASE: not at the end of the list, keep going else: # helps trace what's going on, but not necessary print("Now adding", theList[currIndex], "at index", currIndex) # RECURSIVE CALL: add current element, call on next one return theList[currIndex] + recSumList2(theList, currIndex + 1) def main(): myList = [3, 5, 8, 7, 2, 6, 1] print("\tAdding the list", myList, "together:") ans1 = recSumList1(myList) print("The sum of the list is", ans1) print("\n\tAdding a different way: ") # requires that we give starting index, so start at position 0 ans2 = recSumList2(myList, 0) print("The sum of the list is", ans2) print("\n\n\tAsking for a valid grade using recursion:") ans = recGetGrade() print("You got a grade of", ans) main()