2017-11-10 1 views
0

제 과제를 위해리스트에 1,2,3 개의 원소가 연속적으로 포함되어 있다면 'YES'를 출력하는이 문제를 해결할 수있는 방법을 찾아야합니다. 인덱스 메소드로 인해 [3,1,2,3] 요소가 목록에 포함되어 있으면 작동하지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?파이썬에서의 index() 대안

n=int(input("Enter the number of elements: ")) 

A=[] 
for i in range(0,n): 
    print("Entering element", i) 
    LstEl=int(input("Please enter the element: ")) 
    A.append(LstEl) 


print(A) 
for i in range(0,len(A)): 
    if(1 in A and 2 in A and 3 in A): 
     post1 = A.index(1) 
     post2 = A.index(2) 
     post3 = A.index(3) 
     if(post1 < post2 and post2 < post3): 
      print("YES")   
      break 
     else: 
      print('NO') 
      break 
    else: 
     print("NO") 
     break 

고마워요! 유효한 post1 값을 찾으면

+0

... 반복적으로 슬라이싱하여 평등을 검사합니다. –

+0

외부'for' 루프의 포인트는 무엇입니까? – Blender

+0

이 문제를 해결하기 위해 무차별 방식으로 생각할 수 있습니까? –

답변

1

, 당신은 요소의 연속적인 발생을 찾으려면 색인() 메서드의 다른 매개 변수를 사용

if A[post1:post1+3] == [1, 2, 3]: 
    print('Yes') 
    break 

를 사용하여 순서를 확인할 수 있습니다 '1'.

+0

[1,2,1,2,3] –

1

하나의 옵션은 다음과 같습니다

# find the indices of all `1`s 
one_idxs = (i for (i, v) in enumerate(values) if v == 1) 
for idx in one_idxs: 
    if values[i : i + 3] == [1, 2, 3]: 
     print('YES') 
     break 
else: 
    print('NO') 

더 간결한 방법은

if any(values[i : i + 3] == [1, 2, 3] for (i, v) in enumerate(values) if v == 1): 
    print('YES') 
else: 
    print('NO') 
+0

과 같은 다른 목록에는 해당 방법이 작동하지 않습니다. 변수 목록을 참조 하시겠습니까? –

+0

@JuanPrimos yep – acushner

0

다음 코드는 큰 목록에서 하위 목록을 추출하는 발전기 함수를 사용합니다. 발전기 기능의 역학을 이해하지 못한다면 숙제에 적합하지 않을 수도 있지만, 관심이 있다면 살펴볼 항목이 될 수 있습니다.

# A generator function that returns the n-length sublists of list lst 
def slider(lst, n): 
    start = 0 
    while start + n <= len(lst): 
     yield lst[start:start+n] 
     start += 1 


# A function that will return True if sequence needle exists in 
# haystack, False otherwise 
def list_contains(haystack, needle): 
    for sub in slider(haystack, 3): # Loop through the sublists... 
     if sub == needle:   # ... test for equality ... 
      return True 
    return False 

# Code 
big = [2,4,6,8,0,1,2,3,1,5,7]  # Hardcoded here, could be created 
            # in a loop like you show 

seq = [1,2,3]      # The sequence you're looking for 

print(list_contains(big, seq)) 

당신이 좋아하는 뭔가 발전기 함수의 출력을 볼 수

big = [2,4,6,8,0,1,2,3,1,5,7] 
for sub in slider(big, 3): 
    print(sub) 

출력 :

[2, 4, 6] 
[4, 6, 8] 
[6, 8, 0] 
[8, 0, 1] 
[0, 1, 2] 
[1, 2, 3] 
[2, 3, 1] 
[3, 1, 5] 
[1, 5, 7] 

아니면 더 명확하게 :

# [2, 4, 6, 8, 0, 1, 2, 3, 1, 5, 7] 
    [2, 4, 6] 
     [4, 6, 8] 
     [6, 8, 0] 
      [8, 0, 1] 
       [0, 1, 2] 
        [1, 2, 3] 
        [2, 3, 1] 
         [3, 1, 5] 
          [1, 5, 7]