python - Any alternate to slice sling of integers? -


i attempting make recursive function adds 2 last numbers until there none left. example:

sumdigits(239) 

would equate to:

2+3+9=14 

it difficult because input must integer, cannot sliced without converting it. decided try turn lists because thought pop() method useful this. appears though approach not working. suggestions?

execution:

>>> sumdigits('234') 9 >>> sumdigits('2343436432424') 8 >>>  

code:

def sumdigits(n):     l1 = list(str(n))     if len(l1) > 1:         = int(l1.pop())         b = int(l1.pop())         l1.append(str(a+b))         return sumdigits(int(''.join(l1)))     else:         return n 

with functional tools reduce() problem solved by

from functools import reduce  def sumdigits(n):     return reduce((lambda x, y: int(x) + int(y)), list(str(n))) 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -