2014-01-16 48 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] 

所以实际上交换你逻辑运算符<>反转排序顺序。