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
添加回答
举报