非回文数的逆的总和是回文

时间:2016-02-20 04:55:05

标签: python loops palindrome

我有一项任务,我提示用户输入开始和结束号码。使用此范围,我必须检查起始编号是否小于结束编号,并且它们都大于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()的

1 个答案:

答案 0 :(得分:0)

您的代码结果不好,因为您的内部循环修改了n,外部循环期望每次只增加一个。我认为你需要为内循环中的数字使用不同的变量。对for使用n循环也可能有意义(但由于需要在n中记录max_cycle_length的值检查,这还不足以解决较大的问题。)

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