2016-12-23 9 views
1

a = [1N、1S、1S、2E、2W、1N、2W] そういうリストがあります。それが次のことをする方法で比較する方法はありますか?隣接する値を比較し、類似のペアを削除して新しいリストを比較する

Pseudo code: Iterate over list [1N, 1S, 1S, 2E, 2W, 1N, 2W], 1==1, delete those values. Iterate over 
new list [1S, 2E, 2W, 1N, 2W], 1!=2, move on, 2==2 delete those values. Iterate 
over new list [1S, 1N, 2W], 1==1, delete those values. Answer = 2W 

私がこれまで持っていたもの。

def dirReduc(arr): 
    templist = [] 
    for i in range(1, len(arr)): 
     a = arr[i - 1] 
     b = arr[i] 
     if a == b: 
      templist = (arr[b:]) 
    (templist) 
a = [1, 1, 1, 2, 2, 1, 2] 
print(dirReduc(a) 

テストケースでは正しい値が生成されますが、2つしか得られなくなるまでループを実行する必要があります。私がこんなことをしているところ

+0

コードを書いてみる(とあなたが持っている問題を)私たちはあなたを助けることができるように。 – Lucas

+0

注意してください! 'dirReduc'関数の最後に' return'がありません( 'return templist 'のようなものでしょう)。関数がなければ 'None'を返します。また最後の行で ')'を閉じる必要があります。 – Lucas

答えて

1

問題が分かっている場合は、必要に応じて繰り返し実行するだけです。

a = [1, 1, 1, 2, 2, 1, 2] 
finished = False 
while not finished: # Iterate until finished = True 
    finished = True # That only happens when no repeated elements are found 
    for i in range(len(a)-1): 
     if a[i] == a[i+1]: 
      a.pop(i) # When removing the element i from a, 
      a.pop(i) # now the i + 1 is in the place of i 
      print(a) 
      finished = False 
      break 

これは、生成されます:

[1, 2, 2, 1, 2] 
[1, 1, 2] 
[2] 
関連する問題