0

I have to implement bubble sort as a homework and my python script has to look for 2 command line parameters:

-f that specifies the file path of the input file that contains a number on each line that I have to sort using bubble sort;

-p that, if specified, tells the script to print the sorted list of numbers in the command line.

Also, I have to implement the algorithm in situ, which means I have to only use one list/array/etc without allocating any other temporary list/array/etc or variable to hold one or a part of all the numbers to sort in the algorithm. So, in my script, I only use unsortedList and nothing else to hold the numbers to sort. I have taken the bubble sort algorithm from the following link: Bubble Sort Homework .

Here is my script:

import sys, getopt

def main(argv):
    inputFilePath = ""
    printList = False

    # Traitement pour parser les arguments
    try:
        opts, args = getopt.getopt(argv, "f:p")
    except getopt.GetoptError:
        usage()
        sys.exit()
    for opt, arg in opts:
        if opt in ("-f"):
            inputFilePath = arg
        if opt in ("-p"):
            printList = True

    inputFile = open(inputFilePath, "r")
    unsortedList = [line.rstrip('\n') for line in inputFile]

    sortedList = bubble(unsortedList)
    if printList == True:
        print (sortedList)

def usage():
    print ("""
    Usage: bubble.py -f <filepath> -p
           -f <filepath> [REQUIRED]: specifies the filepath of the input file
           -p            [OPTIONAL]: specifies whether to print the sorted list or not
    """)

# Function found at https://stackoverflow.com/questions/895371/bubble-sort-homework
def bubble(unsortedList):
    length = len(unsortedList) - 1
    isSorted = False

    while not isSorted:
        isSorted = True
        for i in range(length):
            if unsortedList[i] > unsortedList[i+1]:
                isSorted = False
                unsortedList[i], unsortedList[i+1] = unsortedList[i+1], unsortedList[i]

    return unsortedList

if __name__ == "__main__":
    main(sys.argv[1:])

I am having 2 problems with my script:

First, if I do not specify the -f parameter, the script never runs the usage() function, it only tells "No such file or directory: ''". Why isn't my script running the usage() function?

Also, the bubble sort algorithm doesn't seem to work properly. If I run the script, the numbers aren't sorted properly. I can, for example, see 3998 before 403 in the list. But, I have noticed that the numbers ARE sorted, but only from the left of the numbers. For example, I can see 2553, 256, 2562. 256 is clearly not bigger than 2553, but if you take the number from the left, the third character from the left, 6, is bigger than the third character from the left of 2553, which is 5.

How can I solve those two problems?

Thanks for your help.

Community
  • 1
  • 1
Choub890
  • 1,163
  • 1
  • 13
  • 27
  • First, is there a reason you're using `getopt`? [The docs](http://docs.python.org/3/library/getopt.html) explicitly say that, "Users who are unfamiliar with the C `getopt()` function or who would like to write less code and get better help and error messages should consider using the `argparse` module instead." You're obviously not an old hand with C `getopt`, so why would you use this cryptic, C-style module in Python instead of the one it recommends? – abarnert Jan 23 '14 at 02:01
  • Second, don't put two completely separate problems together into a single question. Pick one and ask about just that. Or, even better, just post two separate questions. (You can add links between the two of them to make it obvious they're about the same code.) You'll get better answers, and twice the rep to boot. – abarnert Jan 23 '14 at 02:02
  • Finally, please try to reduce what you post to a [Minimal, Complete, Valid Example](http://stackoverflow.com/help/mcve) that includes just enough code to show the problem you want fixed, not your entire program. – abarnert Jan 23 '14 at 02:03
  • The reason I am using getOpt is because that is what I have read about when looking online. I am new to Python and thought that was what I had to use to check for parameters and flags. Thanks for pointing the argparse module to me, I will take a look at that. – Choub890 Jan 23 '14 at 02:09
  • In general, whenever you're using a Python standard library module, at least skim over the docs. They often have nice short explanations or good examples—and that's also how you find out when you're using something that has a better replacement. – abarnert Jan 23 '14 at 02:15

1 Answers1

5

First, if I do not specify the -f parameter, the script never runs the usage() function, it only tells "No such file or directory: ''". Why isn't my script running the usage() function?

getopt() doesn't know which flags are required and which are optional. It merely checks that you don't pass unspecified flags or omit an argument if a flag requires one with :.

It's up to you to check that -f is passed in if you require it.


Also, the bubble sort algorithm doesn't seem to work properly. If I run the script, the numbers aren't sorted properly. I can, for example, see 3998 before 403 in the list. But, I have noticed that the numbers ARE sorted, but only from the left of the numbers.

That's because your code is actually sorting strings rather than numbers, so it's putting them in lexicographic order. Try converting them to numbers when you read the file in:

unsortedList = [int(line.rstrip('\n')) for line in inputFile]
                ^^^^                 ^

Also, I have to implement the algorithm in situ, which means I have to only use one list/array/etc without allocating any other temporary list/array/etc or variable to hold one or a part of all the numbers to sort in the algorithm.

In that case, I'd recommend removing the return statement from the bubble sort function. The best way to show that you're only using one array is not to create a second variable called sortedList.

bubble(unsortedList)

If your bubble sort call is simply that, without the assignment, then it's clear you must be modifying the original array.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • +1 for the last section about returning `None` from an in-situ function, just like standard `list.sort`. (Well, not +1 because I already gave you +1 and can't give you more, but you know what I mean.) – abarnert Jan 23 '14 at 02:14