Suma cyfr liczby-python

Jeśli chcę znaleźć sumę cyfr liczby, tzn.:

  • Wejście: 932
  • Wyjście: 14, czyli (9 + 3 + 2)

Jaki jest najszybszy sposób, aby to zrobić?

Instynktownie zrobiłem:

sum(int(digit) for digit in str(number))

I znalazłem to w Internecie:

sum(map(int, str(number)))

Które najlepiej stosować dla szybkości i czy są jakieś inne metody, które są jeszcze szybsze?

Author: vaultah, 2013-02-18

11 answers

Możesz to zrobić wyłącznie w liczbach całkowitych, a będzie to najbardziej efektywne:

def sum_digits(n):
    s = 0
    while n:
        s += n % 10
        n //= 10
    return s

Lub z divmod:

def sum_digits2(n):
    s = 0
    while n:
        n, remainder = divmod(n, 10)
        s += remainder
    return s

Ale obie linie, które napisałeś są w porządku.

 

Jeszcze szybsza jest wersja bez rozszerzonych zadań:

def sum_digits3(n):
   r = 0
   while n:
       r, n = r + n % 10, n // 10
   return r

 

> %timeit sum_digits(n)
1000000 loops, best of 3: 574 ns per loop

> %timeit sum_digits2(n)
1000000 loops, best of 3: 716 ns per loop

> %timeit sum_digits3(n)
1000000 loops, best of 3: 479 ns per loop

> %timeit sum(map(int, str(n)))
1000000 loops, best of 3: 1.42 us per loop

> %timeit sum([int(digit) for digit in str(n)])
100000 loops, best of 3: 1.52 us per loop

> %timeit sum(int(digit) for digit in str(n))
100000 loops, best of 3: 2.04 us per loop
 88
Author: Pavel Anossov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-07 17:32:31

Jeśli chcesz sumować cyfry, dopóki nie otrzymasz liczba jednocyfrowa (jedna z moich ulubionych cech liczb podzielnych przez 9) można zrobić:

def digital_root(n):
    x = sum(int(digit) for digit in str(n))
    if x < 10:
        return x
    else:
        return digital_root(x)
Która sama w sobie okazuje się dość szybka...
%timeit digital_root(12312658419614961365)

10000 loops, best of 3: 22.6 µs per loop
 9
Author: d8aninja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 21:13:35

To może pomóc

def digit_sum(n):
    num_str = str(n)
    sum = 0
    for i in range(0, len(num_str)):
        sum += int(num_str[i])
    return sum
 3
Author: Aftab Lateef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-06 09:31:17

Robiąc jakieś wyzwania Codecademy rozwiązałem to tak:

def digit_sum(n):
arr = []
nstr = str(n)
for x in nstr:
    arr.append(int(x))
return sum(arr)
 1
Author: Tsvetelin Tsvetkov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-29 16:20:17

Możesz również użyć tego:

def sum_digits(num):
    num = str(num)
    digitSum = 0
    for i in num:
        digitSum += int(i)
    return digitSum
print sum_digits(875)
 1
Author: Sam Mendes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-08 23:42:48
def digitsum(n):
    result = 0
    for i in range(len(str(n))):
        result = result + int(str(n)[i:i+1])
    return(result)

"result" jest inicjalizowany przez 0.

Wewnątrz pętli for liczba(n) jest przekształcana w łańcuch, który ma być podzielony indeksem pętli (i) i otrzymuje każdą cyfrę. --- >str(n) [ i: i+1]

Ta pokrojona cyfra jest konwertowana z powrotem na liczbę całkowitą ----> int (str (N) [i: i+1])

I dlatego dodawane do wyniku.

 0
Author: Arghyadeep Giri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-22 17:51:52
def sumOfDigits():

    n=int(input("enter digit:")) 
    sum=0
    while n!=0 :

        m=n%10
        n=n/10
        sum=int(sum+m)

    print(sum)

sumOfDigits()
 0
Author: itachi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-21 18:14:36

Najlepszym sposobem jest użycie rozumienia listy:

sum([int(digit) for digit in str(abs(number))])
 -1
Author: dapaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-12 16:17:59
num = 123
dig = 0
sum = 0
while(num > 0):
  dig = int(num%10)
  sum = sum+dig
  num = num/10

Print (sum) / / upewnij się, że dodałeś spację powyżej tej linii

 -1
Author: Jayant Pandey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-05 12:43:30

Możesz spróbować tego

def sumDigits(number):
    sum = 0
    while(number>0):
        lastdigit = number%10
        sum += lastdigit
        number = number//10

    return sum
 -1
Author: Julisam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-13 16:46:56
n = str(input("Enter the number\n"))

list1 = []

for each_number in n:

        list1.append(int(each_number))

print(sum(list1))
 -3
Author: Abdullah Asif,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-09 14:24:05