I am learning recursion algorithms in this book I'm reading and one of the exercises is to make a recursion function that takes as input an integer, a list, string etc and if a list, it adds up all the integers in that list, skipping floats or strings: i.e. sum_ints([3, 3, 'a', 6]) = 12 but I wanted to step it up a notch and give it nested lists to deal with i.e. sum_ints([[[3]], [3, 4], 'a', 6]) = 16 and I cannot get the code to deal with nested lists. Would anyone please give me some hints as to how to code this in? Here is the code I have thus far:
# Developed by: ManOfMystery
'''Creates a recursion function that takes as input an integer, a list, string
etc and if a list, it adds up all the integers in that list, skipping floats
or strings: i.e. sum_ints([[[3]], [3, 4], 'a', 6]) = 16'''
def sum_ints(x):
# If x is an int, it returns x
if isinstance(x, int):
return x
# If x is a string or float, it returns 0
elif isinstance(x, str) or isinstance(x, float):
return 0
# If it gets to end of list, stops the recursion
elif x == []:
return 0
# Checks if x is list and looks at first element and decides whether it is
# a string, float or integer and deals with it
elif isinstance(x, list):
if isinstance(x[0], int):
return x[0] + sum_ints(x[1:])
else:
return 0 + sum_ints(x[1:])
Question
vladmphoto
Hello everyone,
I am learning recursion algorithms in this book I'm reading and one of the exercises is to make a recursion function that takes as input an integer, a list, string etc and if a list, it adds up all the integers in that list, skipping floats or strings: i.e. sum_ints([3, 3, 'a', 6]) = 12 but I wanted to step it up a notch and give it nested lists to deal with i.e. sum_ints([[[3]], [3, 4], 'a', 6]) = 16 and I cannot get the code to deal with nested lists. Would anyone please give me some hints as to how to code this in? Here is the code I have thus far:
# Developed by: ManOfMystery '''Creates a recursion function that takes as input an integer, a list, string etc and if a list, it adds up all the integers in that list, skipping floats or strings: i.e. sum_ints([[[3]], [3, 4], 'a', 6]) = 16''' def sum_ints(x): # If x is an int, it returns x if isinstance(x, int): return x # If x is a string or float, it returns 0 elif isinstance(x, str) or isinstance(x, float): return 0 # If it gets to end of list, stops the recursion elif x == []: return 0 # Checks if x is list and looks at first element and decides whether it is # a string, float or integer and deals with it elif isinstance(x, list): if isinstance(x[0], int): return x[0] + sum_ints(x[1:]) else: return 0 + sum_ints(x[1:])Link to comment
Share on other sites
4 answers to this question
Recommended Posts