I wrote the following code in Python. It does not sort the list. Can anyone help me out?

theList = []

def simpleSort():
    pos = 1
    comps = 0
    while pos < len(theList):
        comps += 1
        if ord(theList[pos]) >= ord(theList[pos - 1]):
            pos += 1
        else:
            temp = theList[pos]
            print(theList[pos])
            theList[pos] = theList[pos - 1]
            print(theList[pos])
            theList[pos - 1] = temp
            if pos == 1:
                pos += 1
            else:
                pos -= 1
    return comps


def main():
    fileName = input("Type a filename: ")
    aFile = open(fileName)
    for line in aFile:
        theList = line.split()
        print("Original List:")
        print(theList)
        comps = simpleSort()
        print("Sorted List:")
        print(theList)
        print("Compares:")
        print(comps)
        

main()

What is purpose of ord at line 8? You only want to sort single characters?
Shouldn't you pass theList as parameter to function?

Edited 5 Years Ago by pyTony: n/a

Among several other things, you're not telling python to do with that file your opening, you're not going to like the output, how about open(file,'r')...

Among several other things, you're not telling python to do with that file your opening, you're not going to like the output, how about open(file,'r')...

But isn't r the default option? Meaning if you don't type anything it will use r. The opening of files is not the issue here. Can anyone help with the sorting? Thanks.

But isn't r the default option? Meaning if you don't type anything it will use r. The opening of files is not the issue here. Can anyone help with the sorting? Thanks.

it's bad practice to be implicit so I guess I wouldn't know. Have you looked up the source of the sorted() function or the sort method of the list class? I would imagine those would be pretty useful. And you need a parameter for that "Simplesort" function, it's not doing anything but returning.....nothing, otherwise.

Edited 5 Years Ago by pyguy62: n/a

This article has been dead for over six months. Start a new discussion instead.