【发布时间】: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