Python 非回文数的倒数之和为回文数
我有一个任务,提示用户输入起始和结束号码。使用这个范围,我必须检查起始数字是否小于结束数字,并且它们都大于一。然后我需要检查范围(包括)内的所有数字,看看它们是否是回文,如果不是,我需要反转数字并将其添加到原始数字,直到得到回文。我还需要在每次通过循环并反转一个数字时跟踪循环长度 这就是我到目前为止所拥有的,我真的不明白我错在哪里Python 非回文数的倒数之和为回文数,python,loops,palindrome,Python,Loops,Palindrome,我有一个任务,提示用户输入起始和结束号码。使用这个范围,我必须检查起始数字是否小于结束数字,并且它们都大于一。然后我需要检查范围(包括)内的所有数字,看看它们是否是回文,如果不是,我需要反转数字并将其添加到原始数字,直到得到回文。我还需要在每次通过循环并反转一个数字时跟踪循环长度 这就是我到目前为止所拥有的,我真的不明白我错在哪里 def rev_num(n): rev_n = 0 while (n > 0): rev_n = rev_n * 10 + (n % 10)
def rev_num(n):
rev_n = 0
while (n > 0):
rev_n = rev_n * 10 + (n % 10)
n = n // 10
return rev_n
def is_palindromic(n):
return (n == rev_num(n))
def main():
# Prompt the user to enter the starting number of the range.
start = eval (input ("Enter starting number of the range: "))
# Prompt the user to enter the ending number of the range.
finish = eval (input ("Enter ending number of the range: "))
# Check that the starting and ending number are greater than 1 and start is smaller than ending number.
while (start >= finish or start < 1 or finish < 1):
start = eval (input ("Enter starting number of the range: "))
finish = eval (input ("Enter ending number of the range: "))
# Initialize variables for cycle length and max cycle length.
cycle_length = 0
max_cycle_length = 0
max_num = 0
n = start
# Write a loop that goes through all the numbers.
while (n <= finish):
cycle_length = 0
# Write the conditions for the Palidromic Reverse Sum.
while (is_palindromic(n) == False):
n += rev_num(n)
cycle_length = cycle_length + 1
#Increment the counter and assign the cycle length to the max cycle length if > or =.
if (cycle_length >= max_cycle_length):
max_cycle_length = cycle_length
max_num = n
counter += 1
# Print the results
print ("The number " + str(max_num) + " has the longest cycle length of " + str(max_cycle_length) + ".")
def rev_num(n):
rev_n=0
而(n>0):
版次n=版次n*10+(n%10)
n=n//10
返回版次
def是回文(n):
返回(n==rev_num(n))
def main():
#提示用户输入范围的起始编号。
开始=评估(输入(“输入范围的开始编号:”)
#提示用户输入范围的结束编号。
finish=eval(输入(“输入范围的结束编号:”))
#检查起始编号和结束编号是否大于1,起始编号是否小于结束编号。
当(开始>=完成或开始<1或结束<1):
开始=评估(输入(“输入范围的开始编号:”)
finish=eval(输入(“输入范围的结束编号:”))
#初始化循环长度和最大循环长度的变量。
循环长度=0
最大循环长度=0
最大数量=0
n=开始
#写一个遍历所有数字的循环。
while(n或=。
如果(循环长度>=最大循环长度):
最大循环长度=循环长度
最大数量=n
计数器+=1
#打印结果
打印(“数字“+str(max_num)+”的最长循环长度为“+str(max_cycle_length)+”)
main()(但由于您还需要在
max\u cycle\u length
检查中记录n
的值,这还不足以解决更大的问题)
使用int(input())
代替eval(input())
。
for n in range(start, finish+1): # for loops are nicer than while loops
x = n # use n's value as initial value for x
cycle_length = 0
while not is_palindromic(x): # inner loop modifies x not n
x += rev_num(x)
cycle_count += 1
if cycle_count > max_cycle_count:
max_cycle_count = cycle_count
max_num = n # use n again here