Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need help with a Python recursion problem: You must include appropriate doc stri

ID: 3796504 • Letter: N

Question

Need help with a Python recursion problem:

You must include appropriate doc strings (e.g. strings that appear on the line following the function header) to the class that clearly and concisely describe what the functions are doing. The functions written for this assignment must be recursive and must not use global variables. The functions may not use loops. In some cases certain built-in Python functions are disallowed. Function that are described as returning values should not do any printing. Please note that local variables are absolutely fine in any of the functions.

Write a recursive function recListSum() that takes an arbitrarily nested list as a parameter and returns the sum of the numbers in the list. You are not allowed to use any list methods in your function other than indexing (lst[i] for some integer i), slicing (lst[i:j] for some integers i and j), or len(). You may assume that the initial value given to the function is a list, and your function does not have to behave in any reasonable way when given something other than a list as a parameter. The list may contain values of any type and you must only take the sum of the ones that are integers or floating point values. The type() function is helpful in determining what values can be found in the list. Numbers found within other collections (tuples, dictionaries, etc.) should not be included in the sum. The following shows the behavior of the function on some sample parameters. Please remember that the examples are just that. Your function must work correctly on all valid parameters, and you may not make any assumptions about the number of nested sublists or the depth of the nesting in the list provided as a parameter to the function:

Python 3.4.1 Shell File Edit Shell Debug Options Windows Help rec List, Sum val rec List Sum 1 hello val rec List Sum (CE1.2 test' CE3 14], 'bye 12], 1, 2) 16.34 recListsum (CCECCE3 14, 101, 11, 61, 51, 91, 31) 37.14 Ln: 37 Col: 4

Explanation / Answer

def recListSum(numList):
'''
Return sum of element of numList which is computed recursively.
'''
if type(numList) is list:
if len(numList) == 0:
return 0;
if len(numList) == 1:
if (type(numList[0]) is int) or (type(numList[0]) is float):
return numList[0]
else:
return 0
elif (type(numList) is int) or (type(numList) is float):
return numList
else:
return 0
  
return recListSum(numList[0]) + recListSum(numList[1:])

print recListSum([])
print recListSum([1,2,3,'hello'])
print recListSum([[1.2, 'test'], [[3.14], 'bye', 12], (1,2)])
print recListSum([[[[[[3.14,10],1],6],5],9],3])

# here is pastebin link of code: http://pastebin.com/B0kDCtbb