質問

So I am new to python and I have a project which requires us to go through a really long tuple list and we have to order the list in descending and ascending order. However, for both my functions I always get ascending order, WHAT IS WRONG? someone please help im really stressed out

def bubblesort_descending(tuple_list):
    j = len(tuple_list)
    made_swap = True
    swaps = 0
    while made_swap:
        made_swap = False
        for cnt in range (j-1):
            if tuple_list[cnt] < tuple_list[cnt+1]:
                tuple_list[cnt], tuple_list[cnt+1] = tuple_list[cnt+1], tuple_list[cnt]
                made_swap = True
                swaps = swaps + 1
    return swaps

Main Program:

elif choice ==  'd':
    unsorted = range(len(numbers))
    shuffle(unsorted)
    print ("Randomised tuple list generated:")
    print
    print (unsorted)

    swaps = bubblesort_descending (unsorted)
    print
    print ("heres the sorted list")
    print
    print (unsorted)
    print
    print (swaps, "swap(s) made")
    print
役に立ちましたか?

解決 2

You need to convert that iterator to a list.

unsorted = range(10)
unsorted_list = list(unsorted)

After this, your code will sort in descending order because you are making a swap if tuple_list[cnt] is less than tuple_list[cnt+1]. If you change the logical operator from "<"to ">" you will get ascending order because after changing, you will make swaps if tuple_list[cnt] is greater than tuple_list[cnt+1]

By naming your list as tuple_list, it is kind of confusing. Because in python lists and tuples are different.
What's the difference between lists and tuples?

他のヒント

The basic difference between ascending and descending sorting order is in the comparison: Here is a bubble sort implementation as taken from http://www.codecodex.com/wiki/Bubble_sort#Python:

def bubble_sort(lst, asc=True):
    lst = list(lst)  # copy collection to list
    for passesLeft in range(len(lst)-1, 0, -1):
        for i in range(passesLeft):
            if asc:
                if lst[i] > lst[i + 1]:
                    lst[i], lst[i + 1] = lst[i + 1], lst[i]
            else:
                if lst[i] < lst[i + 1]:
                    lst[i], lst[i + 1] = lst[i + 1], lst[i]
    return lst

Note: The difference based on the asc parameter?

Example:

>>> xs = [1, 2, 9, 4, 0]
>>> bubble_sort(xs, asc=True)
[0, 1, 2, 4, 9]
>>> bubble_sort(xs, asc=False)
[9, 4, 2, 1, 0]

So in effect swapping your logical operator < to > reverses the sorting order.

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