You've horridly confused your data types. Naming something integer
does not make it an integer. You're fine on the first call. Had you done any rudimentary debugging, you'd have seen the problem: you turn the integer into a list of single-character strings.
When you split the list and recur, you pass that half-list into your function as integer
. When you immediately turn it into a new string with str(integer)
, you get a string something like "['1']"
, rather than a simple character digit. When you explode that into a list, you get ['[', "'", '1', ']', "'"]
as numlist
... and it's a nasty infinite recursion from there.
First, make sure you have a consistent interface for your function: if nothing else, reconstitute the half-string into an integer and feed that value to your recursive call. Second, don't get overly expansive: you can simply convert the integer to a string and work on the individual digits; no need to make a list from that.
Third, see this lovely debug blog for help.
Finally, you might research other solutions on line. This is a common exercise. I'm not telling you to copy the program -- but now that you've given the problem a good attempt, you can learn about the internal processing from others.
To get you moving, here's how I instrumented your code for debugging: print
useful things on enter and exit, and put in a delay (sleep) so I have a chance to interrupt the program before useful info rolls off the screen.
from time import sleep
call = 0
def sum_of_digits(integer):
global call
call += 1
id = call
print("ENTER", call, integer)
numlist = list(str(integer))
print("numlist", numlist)
sleep(1)
if len(numlist) == 0:
result = 0
elif len(numlist) == 1:
result = numlist[0]
else:
midPoint = len(numlist) // 2
result = sum_of_digits(numlist[:midPoint]) + \
sum_of_digits(numlist[midPoint:])
print("LEAVE", id, result)
return result
test = [0, 1, 12]
for case in test:
call = 0
sum_of_digits(case)
print("-------------------------")
Output:
ENTER 1 0
numlist ['0']
LEAVE 1 0
-------------------------
ENTER 1 1
numlist ['1']
LEAVE 1 1
-------------------------
ENTER 1 12
numlist ['1', '2']
ENTER 2 ['1']
numlist ['[', "'", '1', "'", ']']
ENTER 3 ['[', "'"]
numlist ['[', "'", '[', "'", ',', ' ', '"', "'", '"', ']']
ENTER 4 ['[', "'", '[', "'", ',']
numlist ['[', "'", '[', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '[', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ']']
^CTraceback (most recent call last):
File "so.py", line 33, in <module>
sum_of_digits(case)
File "so.py", line 23, in sum_of_digits
result = sum_of_digits(numlist[:midPoint]) + \
File "so.py", line 23, in sum_of_digits
result = sum_of_digits(numlist[:midPoint]) + \
File "so.py", line 23, in sum_of_digits
result = sum_of_digits(numlist[:midPoint]) + \
File "so.py", line 15, in sum_of_digits
sleep(1)
KeyboardInterrupt