2014-01-16 49 views
1

所以我對python很陌生,我有一個項目需要我們經歷一個很長的元組列表,我們必須按降序和升序排列列表。但是,對於我的兩個功能,我總是按升序排列,什麼是錯誤的?有人請幫助我真的壓力太大了在python中對氣泡排序幫助 - 升序和降序

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 

主要課程:

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 
+0

爲什麼你沒有使用[sorted](http://docs.python.org/2/library/functions.html#sorted)? – thefourtheye

+0

@thefourtheye我猜這是一個學習練習。 –

+0

它正在爲我排序正確,降序排列。你確定你發佈了兩個函數嗎? – arocks

回答

1

您需要將該迭代器轉換爲列表。

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

在此之後,你的代碼會按降序進行排序,因爲你是一個交換,如果tuple_list[cnt]小於tuple_list[cnt+1]。如果從「<‘改變邏輯運算符’>」你會得到升序排列,因爲改變後,你會做掉,如果tuple_list[cnt]大於tuple_list[cnt+1]

通過命名您的列表作爲tuple_list,它是一種混亂。因爲在python列表和元組是不同的。
What's the difference between lists and tuples?

+0

實際上Python 2中的''range()''給你一個列表。在Python 3中,它爲您提供''''的迭代器。 –

+0

,因爲他正在使用打印功能(打印())我認爲他沒有使用Python 2.所以他沒有創建一個列表。對於python 3,我不知道。感謝您的信息。根據這個更新我的答案。 – Lafexlos

+0

你不能做這個假設。 ''from __future__ import print_function''。 –

2

的基本區別和之間上升降序排列順序是在比較:這是一個冒泡排序執行取自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 

注:基於asc參數的差異?

例子:

>>> 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] 

所以實際上交換你邏輯運算符<>反轉排序順序。