简体   繁体   中英

Is using ord() wrong in this case?

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 and y 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 one Z unit (score = 26).

But, because you're implicitly increasing the score by ord('A') - 1 for each unit, that won't work. With ord('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):

first_group = sum((ord(item) - ord('A') + 1 for item in a))

That would make your code along the lines of:

def battle(x, y):
    first = sum((ord(item) - ord('A') + 1 for item in x))
    second = sum((ord(item) - ord('A') + 1 for item in y))

    if first > second:
        return x
    if second > first:
        return y
    return "Tie!"

You need to do the actual mapping. For example, 'AA' is 2 and 'Z' is 26 so 'AA' < 'Z' but your solution has 'AA' = 130 and 'Z' = 90 so 'AA' > 'Z'.

You can get there by subtracting ord('A') to get the relative number and adding one:

ord(a) - ord('A') + 1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM