[英]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 我不知道为什么会收到这种错误。.此代码是关于在特定间隔中找到kaprekar数
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 =''
. 例如,如果
p == 1
, midone = '1'
, midtwo =''
。 I don't know the algorithm, but maybe you want to treat an empty string as a 0
? 我不知道算法,但也许您想将空字符串视为
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
. 正如其他人指出的那样,按照书面形式,它试图将空字符串转换为整数,这会导致OP的
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 ). 更重要的是,它不会输出Kaprekar数 , Kaprekar数是平方K可以分为两部分的数字K'和K'' ,从而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.
该OP的节目似乎打算生产号码Ĵ可分成两个部分J“和J‘’,使得J” + J'= J(1)2。 Aside from specious examples such as the numeral 00, the latter sort of number seems unlikely.
除了数字00之类的具体示例外,后一种数字似乎不太可能。
Below is a program that outputs Kaprekar numbers. 下面是一个输出Kaprekar编号的程序。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.