Reputation: 1
Solving a task ("kata") from codewars. Сoncise and simplified description based on how I solved the problem:
Given two lists that contains results of the game for two teams
x
andy
(10 matches always).For example:
x = [1, 2, 3, 4, 2, 1, 1, 2, 2, 3]
y = [0, 0, 0, 0, 1, 3, 4, 3, 4, 4]
Points are awarded for each match as follows:
- if x > y: 3 points (win)
- if x < y: 0 points (loss)
- if x = y: 1 point (tie)
Write a function that returns the number of points team (x) got in the championship by the rules given above.
I wrote the code in two ways.
The first one (using the zip function) - worked. The second (using for loop) - no. (simple comparing operation does not work properly and I can's figured why!). The code is very simple (see below, but the calculation is not happening correctly!).
I.e. sum_x[4] == 2
and sum_y[4] == 1
and result should be equal '3' (x > y => 3), but it get '1' - WHY?!
There is the code for 2 ways of how task was solved:
1 (worked):
sum_x = [1, 2, 3, 4, 2, 1, 1, 2, 2, 3]
sum_y = [0, 0, 0, 0, 1, 3, 4, 3, 4, 4]
def sum_xy():
x = []
for k, l in zip(sum_x, sum_y):
if k > l:
x.append(3)
elif k < l:
x.append(0)
else:
x.append(1)
return x, sum(x)
OUTPUT: ([3, 3, 3, 3, **3**, 0, 0, 0, 0, 0], 15)
2 (does't work!):
sum_x = [1, 2, 3, 4, 2, 1, 1, 2, 2, 3]
sum_y = [0, 0, 0, 0, 1, 3, 4, 3, 4, 4]
def sum_xy():
x = []
for k in sum_x:
for l in sum_y:
if k > l:
x.append(3)
elif k < l:
x.append(0)
else:
x.append(1)
return x, sum(x)
OUTPUT: ([3, 3, 3, 3, **1**, 0, 0, 0, 0, 0], 13)
Why there is 1
when it should be 3
? - That's my question.
Upvotes: 0
Views: 171
Reputation: 1
def score(points):
for team in points:
x, y = team.split(":")
if x > y:
print("3 points")
elif x == y:
print("1 point ")
else:
print("0 point")
score(["4:3", "3:4", "4:4"])
Upvotes: 0
Reputation: 781935
Version 2 is only comparing the first element of sum_x
to each element of sum_y
. It then returns the result at the end of the first iteration of the outer loop. So you get 1
because sum_x[0] == sum_y[4]
.
If you moved the return
statement to the end, it would still be wrong because they it would compare every element of the two lists, not just the corresponding elements. The result would be 100 elements long instead of just 8.
If you don't want to use zip()
, you need to use the indexes to get the corresponding element.
def sum_xy():
x = []
for i, k in enumerate(sum_x):
l = sum_y[i]
if k > l:
x.append(3)
elif k < l:
x.append(0)
else:
x.append(1)
return x, sum(x)
Upvotes: 1