简体   繁体   English

有没有办法重写 if 语句以避免重复这两行代码?

[英]Is there a way to rewrite the if statements to avoid repeating those 2 lines of code?

I wrote insertion_sort function and added an if statement to choose if I want to order de array in ascendent or descendent mode.我写了 insert_sort function 并添加了一个 if 语句来选择是否要以升序或降序模式对数组进行排序。 As you can see in the following code inside the if statements there are 2 lines of code repeated.正如您在 if 语句中的以下代码中看到的那样,重复了 2 行代码。 I would like to know if there is another way to write those ifs so there´s no line repeated.我想知道是否有另一种方法来编写这些如果,所以没有重复的行。 I´ve been thinking about it but I can't think of any alternative.我一直在考虑它,但我想不出任何替代方案。

Thanks in advance.提前致谢。

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

Latest version of the code:最新版本的代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM