I’m an absolute beginner at python and I need to write a code which can differentiate between 2 lists. Overall code works yet, consistently the last element of the list is not being taken into account and lists such as “AT, AC” are being considered the same. I would love some help. Thanks !
JavaScript
x
22
22
1
Seq1 = input( " Enter first sequence ")
2
Seq2 = input(" Enter second sequence ")
3
4
seq1 = list(Seq1)
5
seq2 = list(Seq2)
6
7
def compare_seq(seq1,seq2):
8
if len(seq1) != len(seq2):
9
print(" The sequences differ by their length ")
10
exit()
11
else:
12
for i in range(len(seq1)) :
13
if seq1[i] == seq2[i]:
14
print(" The sequences are the same ")
15
exit()
16
else :
17
print(" Sequences differ by a/mulitple nucleotide ")
18
exit()
19
20
compare_seq(seq1,seq2)
21
22
Advertisement
Answer
You exit the loop too early which is a common mistake:
JavaScript
1
9
1
for i in range(len(seq1)) :
2
if seq1[i] == seq2[i]:
3
print(" The sequences might be the same ") # note "might"
4
# exit() # <- leave this one out
5
else:
6
print(" Sequences differ by a/mulitple nucleotide ")
7
exit()
8
print(" The sequences are the same ") # now you know
9
There is a built-in shortcut for this pattern (all
) which you can combine with zip
to make this more concise:
JavaScript
1
7
1
# ...
2
else:
3
if all(x == y for x, y in zip(seq1, seq2)):
4
print(" The sequences are the same ")
5
else:
6
print(" Sequences differ by a/mulitple nucleotide ")
7
for lists, you can also just check equality:
JavaScript
1
7
1
if seq1 == seq2:
2
print(" The sequences are the same ")
3
elif len(seq1) != len(seq2):
4
print(" The sequences differ by their length ")
5
else:
6
print(" Sequences differ by a/mulitple nucleotide ")
7