2014-01-13 2 views
1

저는 파이썬을 처음 사용하고 온라인 연습을 해왔으며 누군가 아래의 솔루션이 실패하는 이유를 설명 할 수 있는지 궁금합니다. 출력에 표시된대로 각기 다른 오류를 생성하는 두 가지 솔루션이 있습니다. 감사!!파이썬 연습의 두 인스턴스에서 루프가 실패하는 경우

왜 코드의 두 번째 블록에는 변수를 할당해야하지만 처음에는 변수를 할당해야합니까? 변수를 할당하지 않으면 pop index out of range error이됩니다.

문제

반환 하늘의 배열 0을 반환하는 배열의 숫자의 합. 숫자 13은 매우 재수가 많으므로 계산에 포함되지 않으며 숫자 13의 직후에 오는 숫자도 포함되지 않습니다. 만약 두 번째에 당신이 실제로 nums.pop을하려고하는 것처럼

sum13([1, 2, 2, 1]) → 6 
sum13([1, 1]) → 2 
sum13([1, 2, 2, 1, 13]) → 6 

해결 한

def sum13(nums): 
    for i in nums: 
     if i == 13 and (nums.index(i) > len(nums) - 2): 
     nums.pop(nums.index(i)) 
     continue  
     if i == 13 and (nums.index(i) < len(nums) - 1):  
     y = nums.index(i) 
     nums.pop(y) 
     nums.pop(y) + 1    
return sum(nums)  




sum13([13, 1, 2, 13, 2, 1, 13]) → 3    3 OK  
sum13([]) → 0          0 OK  
sum13([13]) → 0         0 OK  
sum13([13, 13]) → 0        0 OK  
sum13([13, 0, 13]) → 0     FAILED 13 X  
sum13([13, 1, 13]) → 0     FAILED 13 X  
sum13([5, 7, 2]) → 14        14 OK  
sum13([5, 13, 2]) → 5        5 OK  
sum13([0]) → 0         0 OK  
sum13([13, 0]) → 0        0 OK  
other tests          OK  

해결이

def sum13(nums): 
    for i in nums: 
     if i == 13 and (nums.index(i) > len(nums) - 2): 
     nums.pop(nums.index(i)) 
     continue  
     if i == 13 and (nums.index(i) < len(nums) - 1):  
     y = nums.index(i) 
     nums.pop(y) 
     nums.pop(y) + 1  
     if i == 13 and len(nums) <= 1: 
     return 0 
    return sum(nums) 


sum13([13, 1, 2, 13, 2, 1, 13]) → 3    3 OK  
sum13([]) → 0          0 OK  
sum13([13]) → 0         0 OK  
sum13([13, 13]) → 0        0 OK  
sum13([13, 0, 13]) → 0        0 OK  
sum13([13, 1, 13]) → 0        0 OK  
sum13([5, 7, 2]) → 14        14 OK  
sum13([5, 13, 2]) → 5      FAILED 0 X  
sum13([0]) → 0          0 OK  
sum13([13, 0]) → 0         0 OK  
other tests        FAILED X 
+4

반복되는 동안 항목을 목록에서 제거하지 마십시오. – geoffspear

+1

'print nums'를 루프 몸체의 시작 부분에 추가하면 정확히 무슨 일이 일어나는지 정리해야합니다. – Daenyth

+0

+1 당신이 시도한 것과 입출력 예제를 보여주기 위해서. – jramirez

답변

0

이 보인다 (Y + 1) , 그 오류 외에도 어쨌든 배열의 값을 팝 했으므로 어쨌든 작동하지 않을 것이므로 색인 값이 변경됩니다.

0

나는 모두에게 동의합니다. 목록을 반복하면서 목록을 수정하고 싶지는 않습니다.

다음은 내가 당신의 문제에 대해 작성한 간단한 해결책입니다.

def sum13(nums): 
    # start unlucky_index at a big number so it can never practically happen 
    # at the beginning 
    unlucky_index = 0xFFFF 
    sum = 0 

    for i, num in enumerate(nums): 

     # if num is 13 save index of that 13 
     if num == 13: 
      unlucky_index = i 
      continue 
     # if this is the next number after the 13 index 
     # then ignore 
     if i == unlucky_index + 1: 
      continue 

     sum += num 

    print "sum =",sum # debug only 

    return sum 
0

의견을 듣고 - 당신이 무엇을하는지 모르는 한 그것을 반복하면서 목록에서 객체를 제거하지 마십시오.

조금 더 많은 다른 코드를 작성했습니다. Pythonic. 그것을보고 어떤 방식 으로든 사용할 수 있는지 확인하십시오.

def sum13(nums): 
    running_total = 0 
    # Make an iterator of the provided numbers. This enables us to call 
    # next on it, even inside the for loop. 
    inums = iter(nums) 
    for n in inums: 

     # Drop this number, and drop next number in the sequence. 
     if n == 13: 
      try: 
       next(inums)  
      # If StopIteration is raised, it means that the current item 
      # was the last in the iterator - break out of the loop 
      except StopIteration: 
       break 
      continue 

     # If not 13, add the current number to the running total 
     else: 
      running_total += n 
    return running_total 
관련 문제