如何通过更改 ONE 运算符来更改我的程序以将列表排序为降序?
How can I alter my program to sort a list into descending order by changing ONE operator?
所以我有这个冒泡排序算法只适用于升序,所以我试图通过传递'ascending'[来调整程序=17=] 或 'descending' 作为函数的参数,当比较列表中的相邻项目时,它将运算符从“>”更改为“<”。我试过了,有人有什么想法吗?我想保持代码原样,并尝试不添加针对每个条件重复整个代码的 if 语句。
array=[5,7,0,4,3,24,-1,83,2,1]
def BubbleSort(alist, order):
position=0
swapmade=True
if order == 'ascending':
symbol = '>'
elif order == 'descending':
symbol = '<'
while swapmade == True:
swapmade=False
for count in range(len(alist)-1):
LB=alist[position]
UB=alist[position+1]
if alist[position] + symbol + alist[position+1]:
LB,UB=UB,LB
alist.remove(alist[position+1])
alist.insert(position, LB)
swapmade=True
position=position+1
if position+1 == len(alist):
position=0
return alist
result = BubbleSort(array, 'ascending')
print(*result)
我看到有多种方法可以满足您的需求。
一种方法是定义一个依赖于参数的比较函数。在交换函数的开头附近 define
comparefunc = (lambda x,y: x < y) if order == 'ascending' else (lambda x,y: x < y)
然后使用语句
if comparefunc(alist[position], alist[position+1]):
一个变体是使用 operator
模块中的预定义比较函数 gt
和 lt
(如@zvone 的评论)而不是 lambda
我使用的功能,如果你愿意导入那个模块。
由于您要对整数进行排序,如果要降序排序,另一种方法是比较值的负数。我会让你弄清楚编码。
既然您想保留已有的代码,您可以使用运算符模块将运算符映射到变量。
因此,除了将 symbol 设置为“<”或“>”之外,您还可以这样做(其中 gt 大于而 lt 小于)
import operator
if order == 'ascending':
op = operator.gt
elif order == 'descending':
op = operator.lt
还有这个
if op(alist[position], alist[position + 1]):
LB, UB = UB, LB
alist.remove(alist[position + 1])
alist.insert(position, LB)
swapmade = True
所以我有这个冒泡排序算法只适用于升序,所以我试图通过传递'ascending'[来调整程序=17=] 或 'descending' 作为函数的参数,当比较列表中的相邻项目时,它将运算符从“>”更改为“<”。我试过了,有人有什么想法吗?我想保持代码原样,并尝试不添加针对每个条件重复整个代码的 if 语句。
array=[5,7,0,4,3,24,-1,83,2,1]
def BubbleSort(alist, order):
position=0
swapmade=True
if order == 'ascending':
symbol = '>'
elif order == 'descending':
symbol = '<'
while swapmade == True:
swapmade=False
for count in range(len(alist)-1):
LB=alist[position]
UB=alist[position+1]
if alist[position] + symbol + alist[position+1]:
LB,UB=UB,LB
alist.remove(alist[position+1])
alist.insert(position, LB)
swapmade=True
position=position+1
if position+1 == len(alist):
position=0
return alist
result = BubbleSort(array, 'ascending')
print(*result)
我看到有多种方法可以满足您的需求。
一种方法是定义一个依赖于参数的比较函数。在交换函数的开头附近 define
comparefunc = (lambda x,y: x < y) if order == 'ascending' else (lambda x,y: x < y)
然后使用语句
if comparefunc(alist[position], alist[position+1]):
一个变体是使用 operator
模块中的预定义比较函数 gt
和 lt
(如@zvone 的评论)而不是 lambda
我使用的功能,如果你愿意导入那个模块。
由于您要对整数进行排序,如果要降序排序,另一种方法是比较值的负数。我会让你弄清楚编码。
既然您想保留已有的代码,您可以使用运算符模块将运算符映射到变量。
因此,除了将 symbol 设置为“<”或“>”之外,您还可以这样做(其中 gt 大于而 lt 小于)
import operator
if order == 'ascending':
op = operator.gt
elif order == 'descending':
op = operator.lt
还有这个
if op(alist[position], alist[position + 1]):
LB, UB = UB, LB
alist.remove(alist[position + 1])
alist.insert(position, LB)
swapmade = True