简体   繁体   中英

Kaprekar Number- ValueError: invalid literal for int() with base 10: ' '. String to int

According to wikipedia , a kaprekar number is a number if the representation of its square in that base can be split into two parts, where the second part has p digits, that add up to the original number. For example, 9*9= 81, which can be written as 8 + 1. Therefore, 81 is a kaprekar number.

The following function must print the kaprekar numbers in the given range that is in the range p and q. However, I am receiving ValueError from line 8 r = int(sqr[d:]) .

def kaprekarNumbers(p, q):
    list = []
    for i in range(p,q+1):
        d = len(str(i))
        sqr = str(i*i)
        l = int(sqr[:d])
        r = int(sqr[d:])
        if l+r == i:
            list.append(i)
    return list


p = int(input())

q = int(input())

result = kaprekarNumbers(p, q)
print(','.join(str(v) for v in result))

Input: 1 100

Error:

 Traceback (most recent call last):
 File "Solution.py", line 18, in <module>
 result = kaprekarNumbers(p, q)
 File "Solution.py", line 8, in kaprekarNumbers
 r = int(sqr[d:])
 ValueError: invalid literal for int() with base 10: ''

Look at the following lines:

    d = len(str(i))
    # -- snip --
    r = int(sqr[d:])

This makes the assumption the the length of str(i) is less than the length of sqr . For input values 0, 1, 2 and 3, this is not the case, so sqr[d:] will end up empty, hence the error.

This happens for inputs p < 4 . Then the value of sqr will just be a single digit string, which means the result of sqr[d:] will be an empty string (and you can't parse the integer value of an empty string).

To fix your problem for the function, you could simply set the value of p to 4 manually if the supplied value is below that.

def kaprekarNumbers(p, q):
    if p < 4: p = 4
    ...

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