converting iteration into a function

时间:2015-04-23 05:18:51

标签: python function iteration

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. This

I have the users input their birthyear, month, and day (all converted to int) and this is the code for 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)

2 个答案:

答案 0 :(得分:2)

You might factor the interesting parts into their own functions.

I'd probably write it like this:

def sum_digits(n):
    return sum(map(int, str(n)))

def magic(y, m, d):
    return sum_digits(sum_digits(y + m + d))

print magic(1997, 1, 1)

答案 1 :(得分:0)

I think this should do the work:

def numerology(z):
    zstr1=str(z)
    accum1=0
    for x in zstr1:
        accum1 += int(x)
    str2=str(accum1)
    accum2=0
    for x in str2:
        accum2 += int(x)
    return accum2

call to function

numerology(first_sum)

btw is a strange way of doing it (to me)

edit: To add to Anonymous's functional way, a recursive one (with list comprehension).

def numerology(z):
    zstr1=list(str(z))
    res=sum([int(i) for i in zstr1])
    if res>10:
        res=numerology(res)
    return res