Stack Overflow Asked by frannmich on January 14, 2021
Okay. I feel a bit silly for having so much trouble with this problem, but essentially, here’s the code I have so far:
def addition_nest(x):
netsum = 0
sublist = []
if isinstance(x, int):
return x
if isinstance(x, list):
for sublist in x:
if sublist == []:
return netsum
else:
netsum = netsum + addition_nest(sublist)
return netsum
I keep getting an error saying the operand + does not work with int and NoneTypes. Any ideas on how I can bypass this? The code basically needs to be able to add up all the integers in a list/nested list, and omit any other elements within the list.
I think the problem is simpler than you and other answers are making it. First rule of recursion is let the recursion do the work:
def addition_nest(unknown):
if isinstance(unknown, list):
if unknown: # not empty
head, *tail = unknown
return addition_nest(head) + addition_nest(tail)
return 0 # empty
if isinstance(unknown, (int, float)):
return unknown
return 0 # neither list nor number
OTOH, if we want to reduce recursion and increase efficiency, we could move in the direction of something like:
def addition_nest(unknown):
if isinstance(unknown, (int, float)):
return unknown
if isinstance(unknown, list):
return sum(map(addition_nest, unknown))
return 0
Which is still recursion, though indirectly as we don't directly call the function from itself but rather hand it off to map()
.
Answered by cdlane on January 14, 2021
This code will get you the expected output.
def addition_nest(x):
netsum = 0
if isinstance(x, int):
# if isinstance(x, (int, float)):
return x
elif isinstance(x, list):
for each_element in x:
if isinstance(each_element, int):
# if isinstance(each_element, (int, float)):
netsum += each_element
elif isinstance(each_element, list):
netsum += addition_nest(each_element)
return netsum
print(addition_nest(25)) ## Output: 25
print(addition_nest([25, 30, 'a'])) ## Output: 55
print(addition_nest([25, 30, ['a', 10, 20]])) ## Output: 85
If you want the above code to work with float
also, replace the if conditions with the commented lines.
In your existing code, you have handled the scenarios for when an element inside the parent list is another list or an integer. But you didn't handle it for other data types. That is the reason for the error you are facing.
Answered by arulmr on January 14, 2021
First of all, the third line is not used and pointless
sublist = []
Second, in cases that it is a list just simply call the function on every element and add together.
def addition_nest(x):
netsum = 0
sublist = []
if isinstance(x, int):
return x
if isinstance(x, list):
for sublist in x:
netsum = netsum + addition_nest(sublist)
return netsum
This will do.
Answered by Frank Chen on January 14, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP