-2

Example : If my input is 582109 , the output should be (5+8+2+1+0+9)+(8+2+1+0+9)+(2+1+0+9)+(1+0+9)+(0+9)+(9)=25+20+12+10+9+9=85

Code:

def getSum(n):
    sum = 0
    while (n != 0):
        sum = sum + int(n % 10) 
        n = int(n/10)
    return sum

n = int(input("Number : "))
print(getSum(n))

This code is just giving sum of all digits in input. how to make it calculate the sum of sum of digits in cyclic order as mentioned in example?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
user13623268
  • 1
  • 1
  • 3

3 Answers3

2

Try this:

def add_digits(string):
    result = 0
    for i in range(len(string)):
        for char in string[i:]:
            result += int(char)
    return result

print(add_digits("582109"))
TheOneMusic
  • 1,776
  • 3
  • 15
  • 39
1

To prevent interating over the digits twice, you can account for the number of times each digit appears in the final sum:

def getSum(n):
    n_string = str(n)
    sum, mult = 0, 1
    for c in n_string:
        sum += mult * int(c)
        mult += 1
    return sum

getSum(582109)
Dallan
  • 504
  • 4
  • 13
  • Smart! You can simplify by doing `for mult, c in enumerate(n_string, 1)`. I posted [my own answer](https://stackoverflow.com/a/62032375/4518341) that uses this, thanks! – wjandrea May 26 '20 at 22:25
0

Here's another solution using the same algorithm as Dallan's answer but as a comprehension using enumerate, and with some inspiration from TheOneMusic's answer:

def add_digits_cyclic(digits):
    return sum(i * int(c) for i, c in enumerate(digits, 1))

print(add_digits_cyclic('582109'))  # -> 85
wjandrea
  • 28,235
  • 9
  • 60
  • 81