简体   繁体   中英

Any alternate to slice sling of integers?

I am attempting to make a recursive function that adds the two last numbers until there are none left. For example:

sumDigits(239)

would equate to:

2+3+9=14

It is difficult because the input must be an integer, which cannot be sliced without converting it. I decided to try to turn it into a lists because I thought the pop() method would be useful for this. It appears as though this approach is not working. Any suggestions?

EXECUTION:

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

CODE:

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

Instead of passing a string you should pass a list of integers:

def sumDigits(l1):
    if len(l1) > 1:
        a = l1.pop()
        b = l1.pop()
        l1.append(a+b)
        return sumDigits(l1)
    else:
        return l1[0]

print sumDigits([2,3, 4])

print sumDigits([2, 3, 4, 3,  4, 3, 6, 4, 3, 2, 4, 2, 4])

The problem with your approach is that:

'23434364324|24|' -> '2343436432|46|' -> '2343436432 | 10' '2343436432 | 10' ,

here now pop will return 0 and 1 , instead of 2 and 10 as you would've expected. Hence the wrong output.

Simple solution:

>>> s = '2343436432424'
>>> sum(int(x) for x in s)
44

With functional tools like reduce() the problem is solved by

from functools import reduce

def sumDigits(n):
    return reduce((lambda x, y: int(x) + int(y)), list(str(n)))

EDIT

The simple solution is:

def sumDigits(n):
    return sum(int(i) for i in str(n))

Upon your answer of my comment the below solution is not applicable.

def sumDigits(n):
    n = [int(i) for i in str(n)]
    return sumDigitsRec(n)

def sumDigitsRec(li):
    if len(li) > 1:
        li[-1] += li.pop()
        return sumDigits(''.join(str(i) for i in li))
    else:
        return li[0]

Since everybody seems intent on solving your homework for you, here's the elegant recursive solution.

def sumDigits(n):
    if n < 10:
        return n
    return n % 10 + sumDigits(n / 10)

As strings:

def sumDigits(n):
    answer = 0
    for num in n:
        answer += int(num)
    return answer

Without slicing, using only an integer input:

def sumDigits(n):
    answer = 0
    while n:
        answer += n%10
        n /= 10
    return answer

If I understand your question correctly, you want to stop summing the digits when the sum is a 2 digit number. I think the bug in your program is that you need if len(l1) > 2: not if len(l1) > 1: to make sure you don't recurse when you have just 2 digits.

you can do it recursively in this way:

def sumDigits(n,s=0):
    if len(n) == 0:
        return s
    else:
        return sumDigits(n[:-1],s+int(n[-1]))

if you want simpler and pytonic way (not recursive) you can do this

>>> s = 2343436432424
>>> sum(map(int,str(s)))
44

All the solutions provided failed to meet the prereqs which were stated in the problem description. This is the correct answer:

Use **kwargs and exceptions to utilize holding variables in recursion function.

For example:

def recursionFunc(x, **kwargs):
    try:
        count = kwargs['count']
    except:
        count = 0

        #Code down here to add num from x to count
        #remove last index on every iteration from x
        #etc

    return recursionFunc(x, count = count)

It's working fine, as the following check will show:

>>> 2343436432424 % 9
8

If you didn't mean for it to be called recursively then just don't do so, ie stop checking the length and just return the sum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM