Skip to content
Advertisement

python – Weight for weight from CodeWars

The code works, but at the same time it outputs a string in which the same value can be reversed. Therefore, it gives an error in tests

Here is the code itself:

def order_weight(strng):
    weight = strng.split(' ')
    t_weight = weight.copy()
    answ = ''
    t_arr = []
    for i in range(len(weight)):
        t_min = 2**64
        t_index = 0
        t_num = 0
        for i, num in enumerate(t_weight):
            t_sum = 0
            for j in num:
                t_sum += int(j)
            if t_sum <= t_min:
                t_min = t_sum
                t_index = i
                t_num = num
        t_arr.append(t_num)
        t_weight.pop(t_index)
    answ = ' '.join(t_arr)
    return answ

enter image description here

Advertisement

Answer

Find it’s harder to follow your logic, but this will be my simple approach:

Please read and compare with yours. It’s passed all tests too.

def count_weight(s):
    return (sum(int(c) for c in s), s)

def order_weight(s):
    return ' '.join(sorted(s.split(' '), key=count_weight))  # use the *weight* as the sort_key here
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement