Search code examples
pythonpython-3.xsortingiterable-unpacking

Used tuple unpacking in Python, can't figure out the logical error


Can't seem to figure out the problem here :

I'm passing a list

vote_sort([("TOD",12),("Football",20),("Baseball",19),("Tennis",10)])

The output that i'm getting

[('Baseball', 19), ('Football', 20), ('TOD', 12), ('Tennis', 10)]

Desired Output :

[('Football', 20), ('Baseball', 19), ('TOD', 12), ('Tennis', 10)]

Thanks For The Help!

def vote_sort(ls):
    firstIndex = -1
    for a, b in ls:
        # EXTRACT THE VOTES = b
        firstIndex += 1
        for index in range(firstIndex+1, len(ls)):
            # COMPARISON,SORT AND SWAP
            if ls[index][1] > b:
                temp = ls[index]
                ls[index] = ls[firstIndex]
                ls[firstIndex] = temp 
    print(ls)

vote_sort([("TOD",12),("Football",20),("Baseball",19),("Tennis",10)])

Solution

  • print(sorted(L, key=lambda k: k[1], reverse=True))
    

    Output:

    [('Football', 20), ('Baseball', 19), ('TOD', 12), ('Tennis', 10)]
    

    EDIT:

    You asked about your code: the major problem is how you treat the outer loop. In the inner loop b changes its position, but you keep comparing with it. For example, at first iteration for both loops position of b is 0, firstIndex is 0 and index is 1. Imagine, you’ve swapped then, at the next iteration for the inner loop you get that b is at position 1, firstIndex still 0, index is 2. Then you will compare elements 1 and 2, but swapping elements 0 and 2. You should in the outer loop iterate not by value, but by index. If you still like writing your own sort function I'd suggest something like this taking your code as base:

    def vote_sort(ls):
        for i in range(len(ls)):
            for j in range(i+1, len(ls)):
                if ls[i][1] > ls[j][1]:
                    tmp = ls[i]
                    ls[i] = ls[j]
                    ls[j] = tmp
    
        print(ls[::-1])