【发布时间】:2020-11-10 14:54:49
【问题描述】:
我想在每次迭代时跟踪冒泡排序算法的中间状态。我试图在循环运行时将它们缓存在字典中,但我一直保持相同的状态
这是我的代码:
def bubblesort(lst):
cache = {}
# Swap the elements to arrange in order
iter = 0
for iter_num in range(len(lst)-1,0,-1):
new_lst = lst
for idx in range(iter_num):
iter += 1
if new_lst[idx]>new_lst[idx+1]:
new_lst[idx], new_lst[idx+1] = new_lst[idx+1], new_lst[idx]
cache[f'iter{iter}'] = new_lst
return cache
这是输出:
{'iter1': [50, 119, 194, 365, 608, 788, 851, 879, 960],
'iter2': [50, 119, 194, 365, 608, 788, 851, 879, 960],
'iter3': [50, 119, 194, 365, 608, 788, 851, 879, 960],
'iter4': [50, 119, 194, 365, 608, 788, 851, 879, 960],
'iter5': [50, 119, 194, 365, 608, 788, 851, 879, 960],
'iter6': [50, 119, 194, 365, 608, 788, 851, 879, 960],
'iter7': [50, 119, 194, 365, 608, 788, 851, 879, 960],
'iter8': [50, 119, 194, 365, 608, 788, 851, 879, 960],
'iter9': [50, 119, 194, 365, 608, 788, 851, 879, 960],
'iter10': [50, 119, 194, 365, 608, 788, 851, 879, 960],
...}
如您所见,它每次都会输出排序列表。我在这里错过了什么?
【问题讨论】:
标签: python deep-copy shallow-copy