我有一系列的名字:队列安德鲁,队列亚历克斯,队列艾米,亚历克斯约翰,亚历克斯彼得,约翰杰米,杰米杰克,约翰亚当
我尝试创建的函数将这些名称排队。名字中有Queue的名字将被正常添加,前面有其他人名字的名字将在队列中这些名字后面排队。所以上面给出的数组的答案是安德鲁,亚历克斯,约翰,杰米,杰克,亚当,彼得,艾米
这是我用来做这件事的函数:
def test(arr):
timer =0
usedname ="pop"
newlist=[]
for i in arr:
new_string = i.replace("MainQueue ","")
newlist.append(new_string)
ans=newlist
for i in range(len(newlist)):
if (len(newlist[i].split()) > 1):
x = newlist[i].split()
y = ans.index(x[0])
name=x[1]
if x[0] == usedname:
timer+=1
newlist.remove(newlist[i])
ans.insert(y+timer,name)
else:
timer =1
newlist.remove(newlist[i])
ans.insert(y+timer,name)
usedname = x[0];
print(' '.join(ans))
但我得到的结果是安德鲁·亚历克斯·约翰·亚当·杰米·杰克·彼得·艾米
我不知道我需要做什么改变才能继续这样做,我觉得我尝试的解决方案可能太复杂了
我发现此功能满足您的要求:
首先,它将所有“队列名称”元素添加到列表中。 然后,它迭代其余的条目,直到
arr
为空(按相反顺序,以便结果正确),并在另一个名称(result.index(a)+1
)的索引后面插入名称(result.insert()
)如果我没有弄错的话,这个算法有最坏的
O(n^2)
和最好的O(n)
编辑
以相反的顺序迭代列表会使它更复杂一些。我们需要从
i=len(arr)
开始,而不是从i=0
开始。然后对于每个迭代,我们将i
减少1。 循环在数组上迭代多次,直到它为空。因此,如果i
到达第0个元素,它需要从arr
的末尾重新开始相关问题 更多 >
编程相关推荐