def recursiveSum(lst):
if len(lst) == 0:
return 0
else:
#print(str(type(lst))+'\n')
num = lst[len(lst)-1]
return recursiveSum(lst.pop()) + num
size = int(input("How many number do you want to enter? = "))
lst=[]
for i in range(size):
lst.append(input("Enter number "+str(i+1)+" = " ))
print(recursiveSum(lst))
In this code i am trying to find sum of list of numbers recursively, this is my first attempt with recursions, i think my approach and algorithm was correct, the list when passed to the recursiveSum() function somehow makes it string in the else part, the commented line when executed ends up printing
class 'list'
class 'str'
I don't understand how the print statement prints both list and str .
Can someone explain this?
I think you forgot to type cast to int when input:
lst.append(int(input("Enter number "+str(i+1)+" = " )))
Two problems:
Fix:
def recursiveSum(lst):
if len(lst) == 0:
return 0
else:
num = lst[0] # use the first one
return recursiveSum(lst[1:]) + num # and recurse on the remaining slice
size = int(input("How many number do you want to enter? = "))
lst=[]
for i in range(size):
lst.append(int(input("Enter number "+str(i+1)+" = " )))
print(recursiveSum(lst))
list.pop()
returns the element popped from the list - not the list-remainder.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.