Here 另一种实现和一些性能测试,实际目标是不更改实际列表,但删除同一列表中的赔率数
第一种方法
# --- Naive Approach Brute Force
def remove_odd(array):
"""Very unefficient Funciton, it has to copy the arr then iterate through it, then calls
remove function, however it does the job, good for small Lists"""
array_copy = array.copy()
for n in array_copy:
if n % 2 != 0:
array.remove(n)
return array
tests = [[4,5,4], [4,5,4,7,9,11], [4,5,4,7,9,11,12,13]]
for test in tests:
print(f'List Before --> {test}')
result = remove_odd(test)
print(f'List After --> {test}')
print('===='*15)
## Other Solution ##
def remove_odd(array):
"""Better Solution, it iterates through the Array once"""
idx = 0
offset = 0 # NOTE: Offset keeps tracks of the jumps after each iteration
max_iter = len(array)
while max_iter:
n = array[idx-offset]
if n % 2 != 0:
offset += 1
array.remove(n)
idx += 1
max_iter -= 1
tests = [[4,5,4], [4,5,4,7,9,11], [4,5,4,7,9,11,12,13]]
for test in tests:
print(f'List Before --> {test}')
result = remove_odd(test)
print(f'List After --> {test}')
print('===='*15)
输出两个函数##
List Before --> [4, 5, 4]
List After --> [4, 4]
============================================================
List Before --> [4, 5, 4, 7, 9, 11]
List After --> [4, 4]
============================================================
List Before --> [4, 5, 4, 7, 9, 11, 12, 13]
List After --> [4, 4, 12]
============================================================
基准测试