I'm trying to write code that count final score using python. The initial code I use was:
initial_score = 50
result = ['T','F','T','T','T','F']
final_score = initial_score
for i in (result):
if i == 'T':
final_score = 10
else:
final_score = -5
print(final_score)
And the result was:
80
Now, I want to make the score/penalty to increase if the results in list are consecutive. If the results are consecutively True (T) so point added to initial_point will increase after each result (10,20,30,etc). Example:
initial_score = 50
result = ['T','T','T','T','T']
So the score for each value in the list will be [10,20,30,40,50]
and the final score will be 200. The same goes for False (F) except the penalty will be (-5,-10,-15,etc). I also want to make constrain, if the consecutive result end it will start from the latest score/penalty. Example:
initial_score = 10
result = ['T','T','F','F','T','T','F','F','F','F','T','T','T']
And the value in the list will be [10,20,-5,-10,20,30,-10,-15,-20,-25,30,40,50]
and the final score will be 125.
How should I do it?
CodePudding user response:
Keep track of the award and penalty, updating it on each right/wrong answer IFF it's the same as the previous answer.
def score(initial, result):
total = initial
award = 10
penalty = 5
for i, prev in zip(result, [None] result):
if i == 'T':
if i == prev:
award = 10
total = award
else:
if i == prev:
penalty = 5
total -= penalty
return total
>>> score(50, ['T','T','T','T','T'])
200
>>> score(10, ['T','T','F','F','T','T','F','F','F','F','T','T','T'])
125
CodePudding user response:
You can use itertools.groupby()
and a little bit of math to compute the point values for each True/False streak:
from itertools import groupby
t_score = 10
t_increment = 10
f_score = -5
f_increment = -5
total_score = initial_score
for key, items in groupby(result):
length = sum(1 for item in items)
if key == 'T':
total_score = t_score * length (length * (length - 1)) // 2 * t_increment
t_score = t_increment * (length - 1)
else:
total_score = f_score * length (length * (length - 1)) // 2 * f_increment
f_score = f_increment * (length - 1)
print(total_score)
This outputs:
125
CodePudding user response:
Keep tracks of the points, rewards and penalties using the dictionaries. And loop over your result
list to reach to the final score.
initial_score = 10
result = ['T','T','F','F','T','T','F','F','F','F','T','T','T']
point_dict = {'T':10, 'F':-5}
increment_dict = {'T':10, 'F':-5}
cycle_num = 0
for i in range(len(result)):
if not cycle_num:
initial_score = point_dict[result[i]]
else:
if result[i] == result[i-1]:
point_dict[result[i]] = increment_dict[result[i]]
initial_score = point_dict[result[i]]
else:
initial_score = point_dict[result[i]]
cycle_num = 1
print(point_dict)
print(initial_score)