2017-03-05 2 views
0

내 프로그램이 회문 수, lychrels 및 non-lychrels 수를 확인합니다. 원래는 'break'와 for 루프를 사용했지만 while 루프를 사용해야했습니다.회 돌이 대신에 회 돌이 - while 회 돌기


내 while 루프는 for 루프와 동일하게 작동하지 않으며 내가 잘못했는지 모른다. - 범위는 num1과 num2 사이 여야합니다. 또한 출력은 프롬프트의 정확한 복사본이어야합니다. 그래서 왜 이렇게 생겼는지 보여줍니다. 감사합니다.

+2

Lychrel 숫자의 존재가 입증 된 적이 없으므로 어떻게 계산할 예정입니까? –

+0

while 루프에서 휴식 시간을 사용하지 않는 이유는 무엇입니까? 질문을 명확히 할 수 있습니까? 정확히 작동하지 않는 것은 무엇입니까? –

답변

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 

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

while가 종료 루프마다 실행된다. for 루프의 break은이를 건너 뜁니다.

두 번째 문제는 flagFalse으로 설정하면 바깥 쪽 while 루프를 멈추게하므로 가장 먼저 발견 한 비 - lychrel 번호가 테스트 한 마지막 번호가됩니다.

가능한 한 조금 변경하려고 시도했습니다. 정보를 전달하는 데 count 변수를 사용하는 대신 isLychrel과 같은 플래그를 추가 할 수 있습니다.

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