![](/img/trans.png)
[英]Python - Not repeating code with if statements, is there another way?
[英]Is there a way to rewrite the if statements to avoid repeating those 2 lines of code?
我写了 insert_sort function 并添加了一个 if 语句来选择是否要以升序或降序模式对数组进行排序。 正如您在 if 语句中的以下代码中看到的那样,重复了 2 行代码。 我想知道是否有另一种方法来编写这些如果,所以没有重复的行。 我一直在考虑它,但我想不出任何替代方案。
提前致谢。
def swap_elements(array, pos1, pos2):
array[pos1], array[pos2] = array[pos2], array[pos1]
return array
def insertion_sort(array, method):
i = 1
while i < len(array):
key = array[i]
j = 0
while j < i:
if method:
if array[j] > key:
key = array[j]
array = swap_elements(array, i, j)
else:
if array[j] < key:
key = array[j]
array = swap_elements(array, i, j)
j += 1
i += 1
return array
最新版本的代码:
def swap_elements(array, pos1, pos2):
array[pos1], array[pos2] = array[pos2], array[pos1]
def insertion_sort(array, method):
i = 1
while i < len(array):
key = array[i]
j = 0
while j < i:
if (method and array[j] > key) or (not method and array[j] < key):
key = array[j]
swap_elements(array, i, j)
j += 1
i += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.