python - replace goto using recursion -


i have simple digit root calculation (ie. sum digits in integer, , if total more 1 digit, repeat process until end single digit answer).

my first impulse calculate sum of digits in initial string, test if result more 1 digit, , if so, goto start of summing suite:

eg.

line = "123456789" sum_digits = 0     # label: if use goto, go 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: # done     print("digital root ", sum_digits); else:     goto label: # need repeat until single digit root number 

but, of course, python doesn't support 'goto' -- guess should written recursive function? neatest way code this?

ps. i'm trying keep code simple understand/explain i'm doing coding exercise son, learning programming

to replace goto idea keep track of line after every iteration find sum.

so, if understand question, following should work:

def find_root(line):     while len(line) > 1:          sum_digits = 0          num in list(line):              sum_digits += int(num)          line = str(sum_digits)     print line   >>find_root("123456789") 9 >>find_root("93856") 4 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -