Home > other >  Python: error invalid literal for int() with base 10
Python: error invalid literal for int() with base 10

Time:10-04

My task is to find how many times we need to multiply digits of a number until only one digit left and count how many "turns" we need to take until that 1 digit left.

Example:

39 -> 3*9=27 -> 2*7=14 -> 1*4=4, so the answer should be 3.

enter image description here

So far I got:

def persistence(n):
    
    count = 1
    sum = int(str(n)[0:1]) * int(str(n)[1:2])

    while(n > 0 or sum > 9):

        sum = int(str(sum)[0:1]) * int(str(sum)[1:2])
        count = count   1
        print(sum)

    print("how many times: "   count) 
    
persistence(39)

So how I approached this task:

  1. I take first 2 digits convert them to str and multiply them.
  2. Already with first sum I go to while loop and keep repeating that.

So, my problem is that I keep getting this: enter image description here

How can I solve it? Or should I try to approach this task differently?

CodePudding user response:

You only have a couple of problems.

  1. The while loop keeps checking n. It only needs to check sum
  2. The final print tries to add an int to a str. Just use print arguments instead.
def persistence(n):
    
    count = 1
    sum = int(str(n)[0:1]) * int(str(n)[1:2])

    while sum > 9:

        sum = int(str(sum)[0:1]) * int(str(sum)[1:2])
        count = count   1
        print(sum)

    print("how many times: ", count) 
    
persistence(39)

Output as expected.

However, you should not use sum as the name of a variable. You can reuse n instead:

def persistence(n):
    
    count = 1
    n = int(str(n)[0:1]) * int(str(n)[1:2])

    while n > 9:

        n = int(str(n)[0:1]) * int(str(n)[1:2])
        count = count   1
        print(n)

    print("how many times: ", count) 

CodePudding user response:

This should work.

def returnLength(n):
    return len(str(n))


def returnProduct(n, pro=1):
    n = str(n)
    for i in n:
        pro *= int(i)
    return pro


n = int(input())
c = 0
while returnLength(n) != 1:
    n = returnProduct(n)
    c  = 1
print(c)

CodePudding user response:

So basically at the start my program had Achilles heel, because it's failed when I had 3 digit number. I read every suggestion very carefully and my final code went like this:

def persistence(n):

    def returnLength(n):
        return len(str(n))
    
    def returnProduct(n, pro=1):
        n = str(n) 
        for i in n:
            pro *= int(i)
        return pro
    
    c = 0

    while n > 9:
        n = returnProduct(n)
        c  = 1
    
    print(c)

However, I still couldn't pass the test nevertheless everything worked fine on VScode and I did some random manual testing (I'm practicing at codewars.com and a lot of people wrote that on this task's test might have a bug). It might be that I can have only one def. I will try to figure that out. Once again, thank you all.

  • Related