Write a pure functional program to add up numbers in a list. Start with the temp
ID: 3576251 • Letter: W
Question
Write a pure functional program to add up numbers in a list. Start with the template given, and do not change anything except where noted. Do not attempt to use loops -- this will only work with recursion. For example:
If the input is:
Then the output will be:
def total(lst):
return (
#### YOUR CODE HERE ####
#### DO NOT WRITE CODE OUTSIDE OF THIS ####
#### RETURN STATEMENT ####
)
def getValue():
try:
return int(input())
except:
return None
v = getValue()
myLst = [v]
while v != None:
v = getValue()
if v != None:
myLst.append(v)
print(total(myLst))
Explanation / Answer
def total(lst):
if len(lst) == 1:
return lst[0]
else:
return lst[0] + total(lst[1:])
def getValue():
try:
return int(input())
except:
return None
v = getValue()
myLst = [v]
while v != None:
v = getValue()
if v != None:
myLst.append(v)
print(total(myLst))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.