回文 - while循环代替循环

问题描述:

所以我的程序检查回文数字,lychrels和非lychrels的数量。最初我使用了'break'和for循环,但是我应该使用while循环。回文 - while循环代替循环


我while循环不起作用一样我的for循环,我不知道我做错了什么? - 范围意味着介于num1和num2之间 此外,输出意味着是提示的精确副本,所以这就是为什么它看起来像这样。 谢谢!

+2

由于Lychrel数的存在从未得到证实,您打算怎样计算它们? –

+0

为什么不在while循环中使用break?你能澄清你的问题吗?什么不工作? –

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