4 回答

TA貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
過早退出循環(huán)是一個(gè)常見的錯(cuò)誤:
for i in range(len(seq1)) :
if seq1[i] == seq2[i]:
print(" The sequences might be the same ") # note "might"
# exit() # <- leave this one out
else:
print(" Sequences differ by a/mulitple nucleotide ")
exit()
print(" The sequences are the same ") # now you know
此模式有一個(gè)內(nèi)置的快捷方式 ( all),您可以將其結(jié)合起來zip使之更加簡(jiǎn)潔:
# ...
else:
if all(x == y for x, y in zip(seq1, seq2)):
print(" The sequences are the same ")
else:
print(" Sequences differ by a/mulitple nucleotide ")
對(duì)于列表,您也可以只檢查相等性:
if seq1 == seq2:
print(" The sequences are the same ")
elif len(seq1) != len(seq2):
print(" The sequences differ by their length ")
else:
print(" Sequences differ by a/mulitple nucleotide ")

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
差一點(diǎn)就解決了,但是有幾個(gè)問題:
Seq1 = input( " Enter first sequence ")
Seq2 = input(" Enter second sequence ")
seq1 = list(Seq1)
seq2 = list(Seq2)
def compare_seq(seq1,seq2):
if len(seq1) != len(seq2):
print(" The sequences differ by their length ")
#exit() No need for this exit as it quits python and makes you have to reopen it everytime you run your function
else:
if seq1 == seq2: #the original loop structure was comparing everysingle item in the list individually, but was then exiting python before completion. So in reality only the first element of each sequence was being compared
print(" The sequences are the same ")
else :
print(" Sequences differ by a/mulitple nucleotide ")
compare_seq(seq1,seq2)
這應(yīng)該可以解決問題。

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個(gè)贊
您只檢查第一個(gè)元素并退出。
Seq1 = input( " Enter first sequence ")
Seq2 = input(" Enter second sequence ")
seq1 = list(Seq1)
seq2 = list(Seq2)
flag = False
def compare_seq(seq1,seq2):
if len(seq1) != len(seq2):
print(" The sequences differ by their length ")
exit()
else:
for i in range(len(seq1)) :
if seq1[i] == seq2[i]:
continue
else :
flag = True
break
if flag == False:
print(" The sequences are the same ")
else:
print(" Sequences differ by a/mulitple nucleotide ")
exit()
compare_seq(seq1,seq2)
上面的代碼應(yīng)該對(duì)你有幫助。它檢查整個(gè)列表,而不是僅僅檢查,如果元素不匹配,則將標(biāo)志更改為 True

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
您可以只檢查兩個(gè)列表的索引處的值是否不相等,否則return true。
例子:
def compare_seq(seq1,seq2):
if len(seq1) != len(seq2):
print("sequences dont share the same length")
return false
for i in range(len(seq1)):
if seq1[i] != seq2[i]:
print("sequences are not the same")
return false
return true
添加回答
舉報(bào)