我的父亲试图让我学习隔离期间的编码,因此告诉我在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.")
嗯,您不需要那个break
。我将把呼叫移到bubblesort()
/ if
块之外的elif
。那两个是我的跳动。
更新:您的bubblesort
函数需要列表中的参数进行排序;函数调用未传递该参数。
在Python中list
不应用作变量名称,因为它是Python保留字。