質問

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.

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top