HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Summing the digits of a sum of digits of a sum

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
summingdigitsthesum

Problem

I'm a beginner in Python, and computer languages in general, and I'm totally stumped on how to format this iteration into a function. The iteration takes the sum of someone's birth year, month, and day and adds it together to create a sum of those numbers, and then the second iteration takes the first sum and adds those numbers together to create a final sum.

I have the users input their birthyear, month, and day (all converted to int) and this is the first sum (Example: A bday of 01/01/1997= 1999):

first_sum=b_yr + b_dy + b_mo


Then the first iteration takes the sum and adds the numbers together (Example: 1999 = 1+9+9+9 = 28):

z = first_sum
zstr1=str(z)
accum1=0
for x in zstr1:
    accum1 += int(x)
(accum1)


Then the second iteration takes the first sum and adds those numbers again to create the final sum (Example: 28 = 2+8 = 10):

str2=str(accum1)
accum2=0
for cnt2 in str2:
    accum2 += int(cnt2)

Solution

Despite your code being cumbersome, I would like to point out that you did well by writing for x in zstr1, iterating over the characters of the string. Python beginners often try to iterate over character indexes instead, resulting in unnatural Python code.

I would decompose the problem differently than @jonrsharpe. sum_digits(n) is a generally useful operation to define as a function.

def sum_digits(n):
    return sum(int(char) for char in str(n))

sum_digits(sum_digits(b_yr + b_mo + b_dy))


Actually, it's not necessary to conflate the summing and the digit breakdown.

def digits(n):
    return [int(char) for char in str(n)]

sum(digits(sum(digits(b_yr + b_mo + b_dy))))


The last line reads just like the problem description: "sum of the digits of the sum of the digits of the year, month, and day".

Here's another implementation of digits(n), using a generator. This avoids stringification.

def digits(n):
    """Produce the base-10 digits of n from least to most significant."""
    while n:
        yield n % 10
        n /= 10

Code Snippets

def sum_digits(n):
    return sum(int(char) for char in str(n))

sum_digits(sum_digits(b_yr + b_mo + b_dy))
def digits(n):
    return [int(char) for char in str(n)]

sum(digits(sum(digits(b_yr + b_mo + b_dy))))
def digits(n):
    """Produce the base-10 digits of n from least to most significant."""
    while n:
        yield n % 10
        n /= 10

Context

StackExchange Code Review Q#87711, answer score: 2

Revisions (0)

No revisions yet.