I have a simple digit root calculation (ie. sum all the digits in an integer, and if the total is more than one digit, repeat the process until you end up with a single digit answer).
My first impulse is to simply calculate the sum of the digits in the initial string, test if the result is more than one digit, and if so, goto the start of the summing suite:
eg.
line = "123456789"
sum_digits = 0
# label: if I could use goto, it would go to here!
n_chars = len(line)
while n_chars > 0:
sum_digits = sum_digits + int(line[0])
line = line[1:]
n_chars -= 1
line = str(sum_digits)
if len(line) < 2: # all done
print("digital root is ", sum_digits);
else:
goto label: # need to repeat until get single digit root number
But, of course, python doesn't support 'goto' -- so I guess this should be written as a recursive function? What is the neatest way to code this?
ps. I'm trying to keep the code very simple to understand/explain as I'm doing this as a coding exercise with my son, who is learning programming
To replace the goto
the idea is to keep track of what the line is after every iteration you find its sum.
So, if I understand your question, the following should work:
def find_root(line):
while len(line) > 1:
sum_digits = 0
for num in list(line):
sum_digits += int(num)
line = str(sum_digits)
print line
>>find_root("123456789")
9
>>find_root("93856")
4