so I need to compare the elements of 2 lists in python,and if they have more than 15 elements in common,it should show a message.I tried to traverse those lists using the for loop,and compare every element from that list,and if they were equal,I made a counter to count my correct answers and if they were above 15 show the message "You passed".But it doesn't work at all,it always says that I passed no matter what Here is the code:
for j in answerList:
for k in answers:
if(k==j):
nr+=1
if(nr>15):
print("You passed")
else:
print("You failed")
Because for answerList
, the answer
is re-iterated, so you should use zip()
for j,k in zip(answerList,answers):
if(k==j):
nr+=1
if(nr>15):
print("You passed")
else:
print("You failed")
Or nr=sum(k==j for j,k in zip(answerList,answers))
By considering len(answers) == len(answerList)
, you can zip()
two lists and perform comparison in one line
n = len([*filter(lambda x: x[0] == x[1], zip(answerList, answers))])
if n > 15:
print("You passed")
else:
print("You failed")
FYI: In your case, the time complexity is O(len^2)
and in this case, it would be O(n)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.