【问题标题】:Bubble Sort help in python - ascending & descending orderpython中的冒泡排序帮助-升序和降序
【发布时间】:2014-01-16 03:23:28
【问题描述】:

所以我是 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

【问题讨论】:

  • 你为什么不用sorted
  • @thefourtheye 我猜这是一个学习练习。
  • 它对我来说是正确的,按降序排列。你确定你发布了这两个函数吗?
  • 是的,它的工作人员我忘了“返回元组列表”哈哈谢谢你的帮助!!

标签: python algorithm bubble-sort


【解决方案1】:

升序降序排序顺序的基本区别在于比较:这里是冒泡排序实现取自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]

因此,实际上将您的 逻辑运算符 &lt; 交换为 &gt; 会颠倒排序顺序。

【讨论】:

    【解决方案2】:

    您需要将该迭代器转换为列表。

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

    在此之后,您的代码将按降序排序,因为如果tuple_list[cnt] 小于tuple_list[cnt+1],您将进行交换。如果您将逻辑运算符从“&lt;”更改为“&gt;”,您将获得升序,因为更改后,如果tuple_list[cnt]大于tuple_list[cnt+1],您将进行交换

    通过将您的列表命名为 tuple_list,这有点令人困惑。因为在python中列表和元组是不同的。
    What's the difference between lists and tuples?

    【讨论】:

    • 其实 Python 2 中的range() 给了你一个列表。在 Python 3 中,它为您提供了 &lt;class 'range'&gt; 的迭代器。
    • 因为他使用打印作为函数 (print()) 我假设他没有使用 python 2。所以他没有创建一个列表。对于python 3,我不知道。感谢您的信息。据此更新我的答案。
    • 你不能做出这样的假设。 from __future__ import print_function.
    • "print_function 2.6.0a2 3.0 PEP 3105: Make print a function" from docs.python.org/2/library/__future__.html -- 在 Python 2.6 中已经存在了很长一段时间。
    • 好的。另一个未知数。再次感谢。 =) 代码应该在 python 2.6+ 中工作,因为 range() 会创建列表。由于它不起作用,这是另一件事让我假设他正在使用 python 3。(似乎只是“正确”的事情)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多