2017-03-05 163 views
0

所以我的程序檢查迴文數字,lychrels和非lychrels的數量。最初我使用了'break'和for循環,但是我應該使用while循環。迴文 - while循環代替循環


我while循環不起作用一樣我的for循環,我不知道我做錯了什麼? - 範圍意味着介於num1和num2之間 此外,輸出意味着是提示的精確副本,所以這就是爲什麼它看起來像這樣。 謝謝!

+2

由於Lychrel數的存在從未得到證實,您打算怎樣計算它們? –

+0

爲什麼不在while循環中使用break?你能澄清你的問題嗎?什麼不工作? –

回答

0

while循環:

while (nums>=num1 and nums<=num2 and flag): 
#for nums in range(num1, num2+1): 
    num_str = str(nums) 
    if num_str == num_str[::-1]: 
     pal += 1 
    else: 
     count = 0 
     num_el = num_str 
     while (count < 60): 
      np_total = int(num_el) + int(num_el [::-1]) 
      count += 1 
      nums_el = str(np_total) 
      num_el = nums_el 
      if num_el == nums_el [::-1]: 
       nonlych += 1 
       flag = False 

     else: 
      lychrel += 1 
      print(nums, "looks like a lychrel number") 
nums += 1 

的 ​​

正在執行每次while循環退出時間。 for循環中的break正在跳過它。

第二個問題是,當flag設置爲False時,它會停止外環while循環,因此您找到的第一個非lychrel編號將是您測試的最後一個編號。

這是我儘可能少地改變的嘗試。您可以添加像isLychrel這樣的標誌,而不是使用count變量傳遞信息。

nums = num1 
while (nums>=num1 and nums<=num2): 
    num_str = str(nums) 
    if num_str == num_str[::-1]: 
     pal += 1 
    else: 
     count = 0 
     num_el = num_str 
     while (count < 60): 
      np_total = int(num_el) + int(num_el [::-1]) 
      count += 1 
      nums_el = str(np_total) 
      num_el = nums_el 
      if num_el == nums_el [::-1]: 
       nonlych += 1 
       count = 999 # breaks while loop 

     if (count != 999): 
      lychrel += 1 
      print(nums, "looks like a lychrel number") 
    nums += 1