2016-02-20 14 views
-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()

+1

使用'int(input())'而不是'eval(input())'。 –

回答

0

您的代碼越來越糟糕的結果,因爲你的內循環改變n,其中外環預計在一次一個只增加。我認爲你需要在內部循環中使用一個不同的變量。對於n使用for循環也是有意義的(但是由於您的也是需要在max_cycle_length檢查中記錄n的值,所以這不足以解決更大的問題)。

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