2017-07-22 10 views
0

私は擬似コードで何をするべきかについて、コーディングとヒットには新しいです。 私はそのための最初の重複関数を定義しています= [1 2 2 3 4 4]それは2を返し、順序付きリストの最初の重複要素の検索

def firstDuplicate(a): 
# put first element into new list (blist) 
# check second element to blist 
# if same, return element and end 
# else, try next blist element 
# if no next element, add to end of blist 
# do the same with third element (counter) and so on until end of list 

alist = list(a) 
blist = list(a[1]) 
bleh = 1 
comp = 2 

if list(a[comp]) == blist[bleh]: 
    return list(a[comp]) # and end 
if else bleh = bleh+1 # and repeat til last blist element 
# to stop? 

else blist = blist+list(a[2]) # append outside of blist? 

これは私がこれまで行ってきたものです。私の次の提案は何ですか?

+0

に興味がある場合は、このウェブサイトですPythonのキャリア構築ではない – bigbounty

+0

@bigbounty何ですか? –

+0

[OK]を、http://python-guide-pt-br.readthedocs.io/en/latest/ – bigbounty

答えて

2

私が正しく理解している場合は、リストを反復処理している間に2回目に表示される最初の番号を返したいとします。これを達成するには、setを使用し、現在のアイテムがすでにセットに含まれているかどうかを確認します(はいの場合はそれを返します)、そうでない場合はセットにアイテムを追加します。 (あなたも、あまり効率的に、リストであることを行うことができます。)の場合

def firstDuplicate(a): 
    set_ = set() 
    for item in a: 
     if item in set_: 
      return item 
     set_.add(item) 
    return None 
+1

すばやく簡単に、完璧に動作します - ありがとう! – Tarae

0

を使用すると、リストの内包することにより、単一のラインコード

a = [10,34,3,5,6,7,6,1,2] 

print [n for i , n in enumerate(a) if n in a[i+1:] and n not in a[:i]][0] 
0
a = [1, 2, 2, 3, 4, 4,] 

def find_it(look_here): 
    have_seen = set() 
    for item in look_here: 
     if item in have_seen: 
      return item 
     have_seen.add(item) 

find_it(a) 
2 
関連する問題