Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop sum of the list until length=1. I really need some help to optimize

num_lst = list(map(int,input()))
b = sum(num_lst)
if len(str(b))==1:
    print(b)
else:
    while True:
        c = str(b)
        new_list = list(map(int,c))
        d = sum(new_list)
        if len(str(d))==1:
            break
    print(d)

These are the code I’ve been trying but the problem is when I run it with too many length of input. It’s timeout. (I am really new to coding as you can see).
Here is the example.
Input: 12345
Output: 6 from 1+2+3+4+5 = 15 and then 1+5 =6.
But when I input like "67896789678967896879678967896789678967896789678969".
It’s timeout.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To solve this problem just change the variable d in the loop by the variable b. As you do with each iteration of the while it will pick up the variable b again, which you didn’t change the value of, thus creating an infinite loop

num_lst = list(map(int,input()))
b = sum(num_lst)
if len(str(b))==1:
    print(b)
else:
    while True:
        c = str(b)
        new_list = list(map(int,c))
        b = sum(new_list)
        if len(str(b))==1:
            break
    print(b)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading