Modified Kaprekar Numbers

Link:

  https://www.hackerrank.com/challenges/kaprekar-numbers

 from __future__ import print_function

 def find_kaprekar(num):

     num_square = str(num ** 2)

     if len(num_square) == 1:
if num == 1:
print (num, end = ' ')
return True
elif len(num_square) % 2 == 0:
d = len(num_square) / 2
if num == int(num_square[0:d]) + int(num_square[d:2*d]):
print (num, end = ' ')
return True
else:
d = len(num_square) // 2
if num == int(num_square[0:d]) + int(num_square[d:(2*d+1)]):
print (num, end = ' ')
return True def main(): p = int(raw_input())
q = int(raw_input()) have_kaprekar_num = False for i in xrange(p, q+1):
if find_kaprekar(i):
have_kaprekar_num = True if have_kaprekar_num == False:
print("INVALID RANGE")
else:
print() main()

//其他1

 def is_kaprekar(n):
squared = str(n ** 2)
mid = len(squared) - len(str(n))
a = int(squared[mid:]) # 这种写法更简便
b = int(squared[:mid]) if len(squared) > 1 else 0
return a + b == n # 直接返回一个判断式子 p = int(raw_input())
q = int(raw_input()) kaprekars = [str(x) for x in xrange(p, q + 1) if is_kaprekar(x)]
print ' '.join(kaprekars) if kaprekars else 'INVALID RANGE' # join函数的使用

//其他2

 import sys

 p = int(sys.stdin.readline())
q = int(sys.stdin.readline()) kaprekar = [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4950, 5050, 7272, 7777, 9999, 17344, 22222, 77778, 82656, 95121, 99999] # 更省资源,因为数量不多,所以干脆一次性算出
ans = [str(k) for k in kaprekar if k>=p and k<=q]
if ans:
print ' '.join(ans)
else:
print 'INVALID RANGE'
上一篇:获取呈现在格表(table)记录的主键


下一篇:mysql随机查询记录的高效率方法