![](/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.