简体   繁体   中英

Kaprekar numbers: I Get ValueError: invalid literal for int() with base 10 ''

I don't know why I get this type of error.. this code is about finding kaprekar numbers in a specefic interval

def find_kaprekar(p,q):   
    numbers = []
    for i in range(p,q):
        str_i = str(i)
        if len(str_i) % 2 == 1:
            midone = str_i[:int((len(str_i)+1)/2)]
            midtwo = str_i[int((len(str_i)+1)/2):]
            if int(midone) + int(midtwo) == i**2:
                numbers.append(i)
        elif len(str_i) % 2 == 0:
            midone = str_i[:int(len(str_i)/2)]
            midtwo = str_i[int(len(str_i)/2):]
            if int(midone) + int(midtwo) == i**2:
                numbers.append(i)

    if len(numbers) == 0:
        print('INVAlID RANGE')
    else:
        print(numbers)

if __name__ == '__main__':
    p = int(input())
    q = int(input())
    find_kaprekar(p, q)

When I run it I always get this:

    if int(midone) + int(midtwo) == i**2:
ValueError: invalid literal for int() with base 10: '
>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

You're grabbing substrings of digits, and one of those substrings is empty.

For instance, if p == 1 , midone = '1' , midtwo ='' . I don't know the algorithm, but maybe you want to treat an empty string as a 0 ?

There are several problems with this program. As others have pointed out, as written it attempts to convert empty strings to integers, which causes the OP's ValueError .

More important, it doesn't output Kaprekar numbers , which is numbers whose square K can be split into two parts K' and K'' , such that K' + K'' =sqrt( K ). The OP's program seems to intend to produce numbers J that can be split into two parts J' and J'' such that J' + J'' = J ^2. Aside from specious examples such as the numeral 00, the latter sort of number seems unlikely.

Below is a program that outputs Kaprekar numbers.

def find_kaprekar(p,q):
    numbers = []
    for candidate in range(p,q):
        candidate_squared = candidate**2
        candidate_squared_string = '%d'%candidate_squared
        for split_point in range(1,len(candidate_squared_string)):
            part_1 = candidate_squared_string[:split_point]
            part_2 = candidate_squared_string[split_point:]
            if int(part_1)+int(part_2)==candidate:
                numbers.append(candidate)
                break
if __name__ == '__main__':
    p = int(input())
    q = int(input())
    find_kaprekar(p, q)

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