简体   繁体   中英

How do I add pieces of lists together all at once and use a while statement to replace my 'if' statement?

Right now I have each piece[] of the list individually converted to int() and then I add them together one by one. I know I'm using a very inefficient method and was hoping for some feedback on how I should go about cleaning this up.

The goal is to take a number like 123 and separating each digit and then adding them together to reach a single digit, 6. The if statement is used so that if I use a larger number like 655 and end up with 16 the number will be separated once again to '1', '6' and summed again to equal 7, a single digit.

Although right now I am limited to numbers of length 3 becasue I don't know how to convert entire strings.

val = input('Enter Value:')
#val = int(val)

#individual value
ival = list(val)
iv0 = int(ival[0])
iv1 = int(ival[1])
iv2 = int(ival[2])
print(iv2)


ivs = (iv0+iv1+iv2)
print(ivs)

if ivs > 9:
    ivs = str(ivs)
    ivss = list(ivs)
    fiv0 = int(ivss[0])
    fiv1 = int(ivss[1])
    fivs = (fiv0+fiv1)
    print(fivs)
    if fivs > 9:
        fivs = str(fivs)
        ivss = list(fivs)
        fiv0 = int(ivss[0])
        fiv1 = int(ivss[1])
        fivs = (fiv0+fiv1)
        print(fivs)
else:
    print(ivs)

You can do this arithmetically, but I think the easiest way to do it is by getting the string representation of the number and working with that.

def sum_digits(n):
    s = sum(int(c) for c in str(n))
    if s > 9:
        return sum_digits(s)
    return s

You could use this code.

d = val
while d > 9:
    d = sum(int(c) for c in str(d))

This acts in just the way you describe. However, there is an easier way. Repeatedly adding the decimal digits of a number is called casting out nines and results in the digital root of the number. This almost equals the remainder of the number when divided by nine, except that you want to get a result of 9 rather than 0 . So easier and faster code is

d = val % 9
if d == 0:
    d = 9

or perhaps the shorter but trickier

d = (val - 1) % 9 + 1

or the even-more-tricky

d = val % 9 or 9

(Note that I included this information in an answer I gave to this previous question from you.)

This should do what you want:

def maths(given_value):
    retval = 0
    for i in given_value:
        retval += int(i)
    return retval

value = raw_input("enter a number: ")

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