2017-03-08 7 views
0

を与えていない私は上記のコードを実装する場合、同じセット変異、なぜ以下のコードは、私はちょうど、セットの変異を実装しようとし、次の午前私に望ましい結果

a=raw_input() 
setA=set(list(map(int,raw_input().split()))) 
N=int(raw_input()) 
for i in range(N): 
    operation=raw_input().split() 
    setB=set(list(map(int,raw_input().split()))) 
    if 'update' in operation[0]: 
     setA.update(setB) 
    elif 'intersection_update' in operation[0]: 
     setA.intersection_update(setB) 
    elif 'symmetric_difference_update' in operation[0]: 
     setA.symmetric_difference_update(setB) 
    elif 'difference_update' in operation[0]: 
     setA.difference_update(setB) 
print sum(setA) 

のコードで、私通知は更新以外の指示は実際には実装されていません... 誰かが私の理由を説明することができます! 入力は=、それらの間のスペースを持つ文字列が 出力密接にこのコードスニペットを見て

+5

:だから私はこれをしようと提案しますか?だから、あなたのエリフは決して実行されません。 –

+0

'operation [0]'にはどのような値がありますか? '' update '== operation [0] 'ではなく、operation [0]'で '' update' 'をテストするのはなぜですか? –

+0

ありがとう@PeterWood :) – deb

答えて

0
if 'update' in operation[0]: 
    setA.update(setB) 
elif 'intersection_update' in operation[0]: 
    setA.intersection_update(setB) 
elif 'symmetric_difference_update' in operation[0]: 
    setA.symmetric_difference_update(setB) 
elif 'difference_update' in operation[0]: 
    setA.difference_update(setB) 

:)事前に おかげであなたの応答のためのセットA中に存在する元素の合計でなければなりません。部分文字列updateoperation[0]にない場合、intersection_updateoperation[0]に存在する可能性はありません。いくつかは他のエリフのために行く。

一方operation[0]にはsymmetric_difference_updateが含まれていますが、それでも対応するelifは呼び出されません。したがって、if 'update' in operation[0]も真であり、これが実行されるためです。したがって、有効な入力であっても、最初のifだけが実行されます。

解決策は何ですか?

条件の順序を変更する必要があります。大きい文字列を上に置き、大きい文字列の下位文字列を下に配置して、大文字小文字以上の文字列が生成されないようにします。解決策の一つ:

if 'symmetric_difference_update' in operation[0]: 
    setA.symmetric_difference_update(setB) 
elif 'difference_update' in operation[0]: 
    setA.difference_update(setB) 
elif 'intersection_update' in operation[0]: 
    setA.intersection_update(setB) 
elif 'update' in operation[0]: 
    setA.update(setB) 

あるいは、より適切に、あなただけの==はなくin確認することができます。それで注文は関係ありません。

+0

@ PeterWoodは、すでにそれを追加しました。ありがとうBTW。 –

+0

理解(y) 説明のためにありがとう:) – deb

0

完全にわからないどのような入力データあなたが処理しているが、イムは、問題は、あなたが正確に一致する文字列の一部ではなく、

A==B 

に一致する

needle in haystack 

を使用していることであることを推測文字列。可能であれば、これを行う前に空白を取り除きたいと思うでしょう。 `update`が運転`でない場合はどのように `intersection_update`、` symmetric_difference_update`と ``操作中に存在してもdifference_update` [0] `ことができ、` [0]

a=raw_input() 
setA=set(list(map(int,raw_input().split()))) 
N=int(raw_input()) 
for i in range(N): 
    operation=raw_input().split() 
    setB=set(list(map(int,raw_input().split()))) 
    command = operation[0].strip() 
    if 'update' == command: 
     setA.update(setB) 
    elif 'intersection_update' == command: 
     setA.intersection_update(setB) 
    elif 'symmetric_difference_update' == command: 
     setA.symmetric_difference_update(setB) 
    elif 'difference_update' == command: 
     setA.difference_update(setB) 
print sum(setA) 
+0

最初の質問に関するコメントを最初に明確にするのが良いと思っています。 –

関連する問題