[英]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.根据wikipedia ,一个 kaprekar 数是一个数字,如果它的正方形在该基数中的表示可以分成两部分,其中第二部分有 p 位,加起来就是原始数字。 For example, 9*9= 81, which can be written as 8 + 1. Therefore, 81 is a kaprekar number.
比如9*9=81,可以写成8+1,所以81是一个卡普雷卡数。
The following function must print the kaprekar numbers in the given range that is in the range p and q.以下 function 必须打印给定范围内的 kaprekar 数字,该范围在 p 和 q 范围内。 However, I am receiving
ValueError
from line 8 r = int(sqr[d:])
.但是,我从第 8 行收到
ValueError
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输入: 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
.这假设
str(i)
的长度小于sqr
的长度。 For input values 0, 1, 2 and 3, this is not the case, so sqr[d:]
will end up empty, hence the error.对于输入值 0、1、2 和 3,情况并非如此,因此
sqr[d:]
最终会为空,因此会出现错误。
This happens for inputs p < 4
.这发生在输入
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).那么
sqr
的值将只是一个数字字符串,这意味着sqr[d:]
的结果将是一个空字符串(并且您无法解析空字符串的 integer 值)。
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.要解决 function 的问题,如果提供的值低于该值,您只需手动将
p
的值设置为 4。
def kaprekarNumbers(p, q):
if p < 4: p = 4
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.