'kattis problem ABC with python3. Works fine in local compiler, but when on submission getting partially right

I am trying the kattis problem ABC (https://open.kattis.com/problems/abc). It works fine on my local compiler, but when I submit, I can't pass all the cases. Can someone have look on my code below though it is bit massy and help me where I am failing:

integer_input = input().split(" ")
character_input = input().upper()
 
#sorting
intCopy = integer_input
for i in range(len(integer_input)-1):
    for j in range(1, len(integer_input)):
        if int(integer_input[i]) > int(integer_input[j]):
            intCopy[i], intCopy[j] = intCopy[j], intCopy[i]

num = []
for i in character_input:
    if i == "A":
        num += intCopy[0]
    elif i == "B":
        num += intCopy[1]
    elif i == "C":
        num += intCopy[2]

for j in num:
    print(int(j), end=" ")


Solution 1:[1]

For starters, intCopy = integer_input doesn't make a copy, it creates an alias. integer_input and intCopy refer to the same list in memory, and modifying one modifies the other. Use intCopy = integer_input[:] if you intended to copy. That said, the sorting appears to work for all permutations of three numbers, so I'd just skip the confusing extra variable.

The main problem is failure to test on multi-digit numbers (the input can run up to 100). If you tried one of these you'd see the problem immediately:

> py abc.py
100 99 98
ABC
9 8 9 9 1 0 0

Printing the data structures to see where things go wrong leads us to the three lines that look like:

        num += intCopy[0]

...where num is a list.

Why is this a problem? If you print(num) after building it, you can see it looks like ['9', '8', '9', '9', '1', '0', '0']. Let's see how += works on lists and strings:

>>> L = []
>>> L += "1234"
>>> L
['1', '2', '3', '4']

So += is an .extend rather than .append semantic. You can fix this by using num.append(intCopy[0]), num += [intCopy[0]], or simply avoiding the intermediate list altogether and printing the element on the spot.

That said, I'd take advantage of Python's built-in sort along with a dictionary to look up the proper order:

order = dict(zip("ABC", sorted(input().split(), key=int)))
print(*map(order.get, input()), sep=" ")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1