2015-07-19 39 views
-1

我的問題在於我的第二個功能代碼。如何比較一個字符串和一個字符串的列表,從列表中返回最佳匹配字符串?

這是我的代碼到目前爲止.... DEF西米(D1,D2): dna_1 = d1.lower() dna_2 = d2.lower() LST = [] I = 0 而我< LEN(dna_1): 如果dna_1 [I] == dna_2 [I]: lst.append(1) I + = 1個 返回LEN(LST)/ LEN(D1)

def match(list_1, d , s): 
    dna = [] 
    for item in list_1: 
     dna.append(simi(item, d)) 
     if max(dna) < s: 
      return None 
    return list_1[max(dna)] 
+0

你是否刻意故意搞砸了嗎?我猜不是...... – jonnybazookatone

+0

你應該定義什麼是「最佳匹配」,以及如何衡量。 – alfasin

+0

如果您逐步瀏覽您的代碼。這很清楚爲什麼你沒有得到任何結果。 'TACgtAttaCGT'按順序匹配10次。 len(lst)/ len(d1)返回0,您追加。 max(dna)返回0,小於0.8,因此退出。 – jonnybazookatone

回答

0

你有兩個問題,第一個是你在嘗試所有的麝香葡萄酒之前在循環中return nts,其次你的功能simi(item, d)返回一個浮動,如果它工作正常,所以試圖索引一個列表float也將失敗。您的代碼無法做任何事情,除了錯誤或返回None

我想你想保持最佳的軌道每次迭代並返回上那是什麼simi距離計算是基於最佳的項目,如果simi是> S或否則返回None:

def match(list_1, d , s): 
    best = None 
    mx = float("-inf") 
    for item in list_1: 
     f = simi(item, d) 
     if f > mx: 
      mx = f 
      best = item 
    return best if mx > s else None 

您還可以在西米使用範圍,而不是你的while循環的一個列表比較:

def simi(d1,d2): 
    dna_1 = d1.lower() 
    dna_2 = d2.lower() 
    lst = [1 for i in range(len(dna_1)) if dna_1[i] == dna_2[i] ] 
    return len(lst)/len(dna_1) 

但如果你只是想每次加1,他們的條件是真的,你可以用和:

def simi(d1,d2): 
    dna_1 = d1.lower() 
    dna_2 = d2.lower() 
    sm = sum(dna_1[i] == dna_2[i] for i in range(len(dna_1))) 
    return sm/len(dna_1) 
+0

非常感謝。有用! –

+0

@ToffeeH,不用擔心,你可以做很多其他的方法,但這似乎是最容易理解的 –

0

使用一些內建的:

from functools import partial 
similarity_with_sample = partial(simi, 'TACgtAcGaCGT') 

現在similarity_with_sample是一個函數,它有一個參數,並與 'TACgtAcGaCGT' 返回其相似性。

現在使用它作爲內置max函數的關鍵參數:

best_match = max(list_of_samples, key=similarity_with_sample) 

我不知道你的s變量做。

相關問題