2017-11-10 3 views
0

私の割り当てでは、リストに要素1,2,3が連続して含まれている場合、この問題を回避する方法を見つける必要があります。インデックスメソッドのためにリストに要素[3,1,2,3]が含まれている場合は機能しません。これを回避するにはどうしたらいいですか?Pythonの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 

ありがとうございます!

+0

...反復的にスライスし、等価性をチェックすることによって。 –

+0

外側の 'for'ループのポイントは何ですか? – Blender

+0

これを解決するための強引な方法はありますか? –

答えて

1

有効なpost1値を見つけたら、要素の連続を見つけるために、インデックス()メソッドのその他のパラメータを使用し

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]