减少程序的时间复杂度

时间:2017-09-25 18:56:51

标签: python-3.x time-complexity

我编写了一个函数来删除给定列表中指定的项目。

def remove_given_elements(arr1) :
    b = []
    x = int(input("Enter the number of items to be removed :"))
    for i in range(x) :
        y = int(input("Enter the position to be removed :"))
        b.append(y)

    arr3 = []
    pos = 0

    for i in range(len(arr1)) :
        arr3.append(arr1[i])
        for j in range(len(b)):
            if pos == b[j]:
                arr3.pop(b[j])
                arr3.append(None)
        pos += 1

    arr4 = []

    for i in arr3:
        if i != None :
            arr4.append(i)

    return arr4

a = [100,200,323,434,512,656]
print("After removing elements",remove_given_elements(a))

输出:

Enter the number of items to be removed :3
Enter the position to be removed :1
Enter the position to be removed :3
Enter the position to be removed :4
After removing elements [100, 323, 656]

因为,我是编程新手。我真的不知道任何方法来减少我最糟糕的时间复杂性。感谢任何形式的帮助或请指导我使用适当的方法来降低时间复杂度。

1 个答案:

答案 0 :(得分:0)

您可以在之前询问这些职位并将其存储在元组中。然后应用该功能。

def remove(_list, pos):
    return [v for i, v in enumerate(_list) if i not in pos]

positions = (1, 2, 3)
l = [1, 2, 3, 4, 5, 6, 7]
result = remove(l, positions)
print(result)

该函数返回List Comprehension