在数学中,给定基数的Kaprekar数是一个非负整数,该基数的方形表示可以分成两部分,再次加起来原始数字。例如,45是Kaprekar数,因为45²= 2025和20 + 25 = 45 我想在两个整数p和q之间打印所有Kaprekar数字
def kaprekarNumbers(p, q):
for i in range(int(p),int(q)):
square = str(i ** 2)
if len(square) % 2 == 0:
p1 , p2 = square[:len(square)/2] , square[len(square)/2:]
else:
p1 , p2 = square[:int(len(square)/2)] , square[int(len(square)/2) :]
if int(p1) + int(p2) == int(i):
print(i , end = '')
错误: 编译器消息:
Runtime Error
Error(stderr) :
Traceback (most recent call last):
File "solution.py", line 26, in <module>
kaprekarNumbers(p, q)
File "solution.py", line 17, in kaprekarNumbers
if int(p1) + int(p2) == int(i):
ValueError: invalid literal for int() with base 10: ''
感谢任何帮助。
答案 0 :(得分:1)
如果p1
是[0,3]范围内的整数,因此其正方形是一位数整数,那么您对正方形字符串版本的拆分将为{{1}生成一个空字符串}。 int(&#39;&#39;)是一个错误。您必须在尝试转换之前检查该值:
if len(square) >= 2:
# Put your existing code here;
# If square is only a single digit, there's no use splitting the result.
更好的是,覆盖一位数的案例,因此您选择1
作为有效数字:
if p1 == '':
p1 = '0' # Force a leading zero.
if int(p1) + int(p2) == int(i):
答案 1 :(得分:1)
这是一个更高级的实现(当你更熟悉 Python 时)。
code.py :
import sys
def kaprekar(n, base=10):
#if i <= 0:
# return False
square = n ** 2
splitter = base
while True:
div, mod = divmod(square, splitter)
if mod and div + mod == n:
return True
if splitter >= square:
return False
splitter *= base
return False
def print_kaprekars(p, q, base=10):
for i in range(p, q):
if kaprekar(i, base=base):
print(i)
def main():
lo = 0
hi = 1000
base = 10
print("Printing Kaprekar numbers (!!! base 10 representation !!!) between {:d} and {:d} in base {:d}".format(lo, hi, base))
print_kaprekars(lo, hi, base=base)
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main()
备注强>:
kaprekar
功能:
splitter
(向右 - >向左)“持有”平方数字中的“位置”,使用[Python]: divmod(a, b)计算2部分<强>输出强>:
(py35x64_test) e:\Work\Dev\StackOverflow\q050846444>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32 Printing Kaprekar numbers (!!! base 10 representation !!!) between 0 and 1000 in base 10 1 9 45 55 99 297 703 999