In my code, I am doing a matching system where you have two lists and the code adds one to a variable for every item in the list that is in the same index and the same item as the other list otherwise it adds one to the other variable it then puts both of the numbers in a list and prints the list.
def report(ticket,winner):
kiss = []
Love = []
x = 0
y = 0
for number in ticket:
if number in winner:
x +=1
elif ticket not in winner:
y += 1
kiss.append(x)
kiss.append(y)
print kiss
an error is like this the input is, report([1,2],[1,2,3]) I want it to add two to the x becuase two of them are in thr correct place and are the same then it needs to add one to the y because its there and not matching but it gives me out: [2,0] also if I put in report([1,3],[1,2,3]) it gives me [2,0] even thoue there not in the same index. That output should be [1,2].
Based on the logic you describe there are a few problems that your code needs to implement. Mainly, in python the in
operator checks if an item exists anywhere in a list
, so for your examples that will always be True
and you get that unexpected output.
Instead we want to check each item in the ticket
list against each item in the winner
list at the same index , so we must specify the index when checking each number.
Try this:
def report(ticket,winner):
kiss = []
Love = []
x = 0
y = 0
# because we are checking different length lists, set ticket to longest list
if len(ticket) > len(winner):
pass
elif len(winner) > len(ticket):
temp = ticket
ticket = winner
winner = temp
for i, number in enumerate(ticket):
try:
if winner[i] == number:
x+=1
else:
y+=1
except IndexError:
y+=1
kiss.append(x)
kiss.append(y)
print kiss
l1 = [1,2]
l2 = [1,2,3]
report(l1, l2) # prints [2, 1]
l1 = [1,3]
l2 = [1,2,3]
report(l1, l2) # prints [1, 2]
Are these your expected outputs?
Hope this helps.
Here's a slightly shorter version using zip
.
def report(ticket, winner):
z = sum(1 for x, y in zip(ticket, winner) if x == y)
return [z, max(len(ticket), len(winner)) - z]
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.