Comparing two lists and "looking back"
How would you approach comparing two lists and "looking back"?
I'm comparing the elements of two lists like this:
score = 0
for (x,y) in zip(seqA,seqB):
if x == y:
score = score +1
if x !=y :
score = 开发者_开发百科score - 1
Now I would like score + 3
if the previous pair was a match, so basically I would have to "look back" one iteration.
Just save the result of the last match.
score = 0
prev = 0
for (x,y) in zip(seqA,seqB):
if x == y:
if prev == 1:
score = score +3
else:
score = score +1
prev = 1
if x !=y :
score = score - 1
prev = 0
There may be a more direct way, but being explicit is not bad either.
The idea to add introduce a variable which tells which amount to add next time we have a match.
score = 0
matchPts = 1 // by default, we add 1
for (x,y) in zip(seqA,seqB):
if x == y:
score = score + matchPts
matchPts = 3
if x !=y :
score = score - 1
matchPts = 1
A more sophisticated reward scale for multiple consecutive matches could be introduced with a few changes:
score = 0
consecutiveMatches = 0
for (x,y) in zip(seqA,seqB):
if x == y:
consecutiveMatches += 1
reward = 1
if consecutiveMatches == 2:
reward = 3;
if consecutiveMatches > 2 :
reward = 5;
if consecutiveMatches > 5 :
reward = 100; // jackpot ;-)
// etc.
score += reward
else:
score -= 1
consecutiveMatches = 0
score = 0
previousMatch == False
for (x,y) in zip(seqa, seqb):
if x==y && previousMatch:
score += 3
elif x==y:
score += 1
previousMatch = True
else:
score -= 1
prviousMatch = False
Similar to how others have done this, but I'd rather use variable names like "correct" rather than seeing "x == y" all over the place...
# Create a list of whether an answer was "correct". results = [x == y for (x,y) in zip(seqA, seqB)] score = 0 last_correct = False for current_correct in results: if current_correct and last_correct: score += 3 elif current_correct: score += 1 else: score -= 1 last_correct = current_correct print score
精彩评论