I'm solving a codewar question - there are two groups containing characters with their own power (A = 1, B = 2, C = 3 . . . Z = 26). Strings consist of uppercase letters only. As only two groups fight against each other, group whose total power (A + B + C ...) is bigger wins. If the powers are equal, it's a tie.
I just converted x and y into lists and used ord() to convert the characters into numbers. And I compared the sum of their numbers using if statements. However, my code still makes a few errors (passed: 103 failed: 5). What is a problem in my code?
Here is my code...
def battle(x, y):
z = []
for a in x:
z.append(ord(a))
first_group = sum(z)
p = []
for b in y:
p.append(ord(b))
second_group = sum(p)
if first_group > second_group:
return x
elif first_group < second_group:
return y
else:
return "Tie!"
No, using
ord()
is perfectly fine in this case provided you use it correctly :-)Assuming the conditions are as you state (
x
andy
being an iterable collection (string, list, etc) of uppercase letters), that will work but it's only guaranteed for teams of the same size.By that, I mean a team of twenty-five
A
units (score = 25) should lose to a team of oneZ
unit (score = 26).But, because you're implicitly increasing the score by
ord('A') - 1
for each unit, that won't work. Withord('A')
being 65, the A team gets a score of 1625, while the Z team gets 90.The score you use has to be constructed for the actual scores of each unit, something like (making the calculation a little more succinct in the process):
That would make your code along the lines of: