-1
我有一個任務,我提示用戶輸入開始和結束數字。使用這個範圍,我必須檢查起始數字是否小於結束數字,並且它們都大於1。然後我需要檢查範圍(包含)中的所有數字,看看它們是不是迴文,如果它們不是,我需要將該數字反轉並將其添加到原始數據中,直到我找到迴文。每次我通過循環並反轉一個數字時,我也需要跟蹤循環長度。非迴文數字反轉的總和是迴文數字
這是我到目前爲止,我真的不明白我要去哪裏錯了。
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) + ".")
的main()
使用'int(input())'而不是'eval(input())'。 –