我试图在不使用
sort()
、可变默认参数、循环或函数外部变量的情况下在 Python 中组织列表。
我唯一的基本选项是切片,但我不确定如何设置切片来将每个值与前面的值进行比较。
def ascending_nums(numbahs):
if len(numbahs) == 1:
return False #set a base case where if only one numbah is entered we return false
else:
ascending = ascending_nums(numbahs[::1])
if numbahs[0:] < ascending:
return True
print(ascending_nums([1,2,3,4,5,6]))
这就是我目前所拥有的,不幸的是,由于基本案例的设置方式,它超出了递归限制。
代码不应该排序,只返回列表是否排序。我能够提交一个解决方案,稍后我会上传它。
有没有特定的原因不能使用 sort()?您可以使用 key= kwarg 获得非常有创意的东西。
标准冒泡排序看起来像这样:
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
swapped = False
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if (swapped == False):
break
找到
另外,我敢肯定之前有人问过你的问题。在此处提问之前,请参考其他答案或谷歌。 Stackoverflow 有很多问题已经得到解答。