4 回答

TA貢獻1155條經驗 獲得超0個贊
過早退出循環是一個常見的錯誤:
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
此模式有一個內置的快捷方式 ( all),您可以將其結合起來zip使之更加簡潔:
# ...
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 ")
對于列表,您也可以只檢查相等性:
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貢獻1816條經驗 獲得超6個贊
差一點就解決了,但是有幾個問題:
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)
這應該可以解決問題。

TA貢獻1876條經驗 獲得超5個贊
您只檢查第一個元素并退出。
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)
上面的代碼應該對你有幫助。它檢查整個列表,而不是僅僅檢查,如果元素不匹配,則將標志更改為 True

TA貢獻1886條經驗 獲得超2個贊
您可以只檢查兩個列表的索引處的值是否不相等,否則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
添加回答
舉報