【问题标题】:Issues making a random number bubble sort in python在 python 中进行随机数冒泡排序的问题
【发布时间】:2020-08-12 12:30:09
【问题描述】:

我父亲试图让我在隔离期间学习如何编码,所以告诉我在 python 中进行随机数冒泡排序。用户应该输入是否要查看从最大到最小的数字,反之亦然,然后创建一个随机数字列表并对它们进行排序。我有点卡住了,不知道该去哪里。

代码如下

import random


def bubble_sort(list):
    # We go through the list as many times as there are elements
    for i in range(len(list)):
        # We want the last pair of adjacent elements to be (n-2, n-1)
        for j in range(len(list) - 1):
            if list[j] > list[j+1]:
                # Swap
                list[j], list[j+1] = list[j+1], list[j]





correct=False
upordownuni=False

list = []

for i in range(0,100):
    x = random.randint(1,10)
    list.append(x)


while correct==False:
    print("Do you want the list to be sorted up or down?")
    upordown = input ("Type up or down for what you want\n")
    if upordown==("up"):
        upordownuni=True
        break
        bubble_sort()
    elif upordown==("down"):
            break
            bubble_sort()
    else:
        print("Invalid! Please input up or down.")

【问题讨论】:

    标签: python sorting random numbers generator


    【解决方案1】:

    好吧,你不需要那个break。我会把对bubblesort() 的调用放在if/elif 块之外。这两个人让我大吃一惊。

    更新: 您的bubblesort 函数需要列表的参数进行排序;函数调用没有传递那个参数。

    在 Python 中,list 不应用作变量名,因为这是 Python 的保留字。

    【讨论】:

    • @WOMP 能解决你的问题吗?
    • 不完全是因为我不知道如何从最高到最低过滤排序列表,反之亦然
    • 快速浏览一下,您的排序看起来很合理。运行程序时会发生什么?
    • 当我尝试调用冒泡排序时,没有任何反应
    • 你应该得到一个错误,因为我现在注意到你定义了函数来接受一个参数,但是你没有在你调用函数时传递一个参数。另外,你不应该使用list作为变量名,因为这是python中的保留字
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2020-12-19
    • 1970-01-01
    相关资源
    最近更新 更多