Search code examples
python-3.xlistalgorithmbubble-sort

Why don't these modified bubble sort algorithms produce the same order in python3?


Objective: to order list by first two characters only, when comparing two elements from a list if they are the same then keep the original order.

Snippet #1

l= []
for i in range(int(input())):
    l.append(input().split())

    for i, j in enumerate(l):
        for b, c in enumerate(l[:-1]):
            if l[b][:2] > l[b+1][:2]:
                l[b],l[b+1] = l[b+1], l[b]
l = [x[0] for x in l]
print( '\n'.join(str(p) for p in l))

The output from #1: The items are alphabetical when considering the entire text, but I only want to consider the first two characters of each string and compare those. When they are the same, I want the original order of those which were compared.

enter image description here

Snippet #2

l = ['Hilbert','Godel','Poincare', 'Ramanujan','Pochhammmer']
for i, j in enumerate(l):
    for b, c in enumerate(l[:-1]):
        if l[b][:2] > l[b+1][:2]:
            l[b],l[b+1] = l[b+1], l[b]
#l = [x[0] for x in l]
print( '\n'.join(str(p) for p in l))

Output from #2: This output is what I was expecting.

enter image description here


Solution

  • In the first algorithm when you use .split() you create a list of lists. So your variable (l) is equal to : [['Hilbert'], ['Godel'], ['Poincare'], ['Ramanujan'], ['Pochammer']] (sorry if I misspelled) so when you ask l[b][:2] you are asking for the first two elements of the list ['Poincare'] which is the list in position b of your initial list, and it is equal to ['Poincare']. So when it gets to ['Poincare'] > ['Pochammer'] it gives 'True'. Given that your lists are composed of only one element (ex. ['Hilbert']) it is able to sort them in the right way and the only problem is with ['Poincare'] - ['Pochammer'] Next time just do not use .split() in this situation but try with l.append(input('')). The .split() is better used for something like 'A B C D E'.split() or something like that.