a={}#dictionary
b=0
while(stack.is_empty()==False):
b=b+1
a={b:stack.pop()}
else:
for i in range(b, 0, -1):
stack.push(a[i])
我認爲這應該工作,但它沒有, 關鍵錯誤和空棧錯誤提出如何扭轉堆棧不返回任何東西
a={}#dictionary
b=0
while(stack.is_empty()==False):
b=b+1
a={b:stack.pop()}
else:
for i in range(b, 0, -1):
stack.push(a[i])
我認爲這應該工作,但它沒有, 關鍵錯誤和空棧錯誤提出如何扭轉堆棧不返回任何東西
逆轉堆棧,可以考慮堆棧的列表,並做到:
stack.reverse()
,而不是彈出和備用棧推。從Python 2 documentation:
反轉列表中的元素,在地方
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
編輯:作爲改寫由提問者,如果你想扭轉堆到一個新的,你可以這樣做:
def reverse_and_return(stack):
newstack = [] # New list/stack
for element in stack:
newstack.insert(0, element) # Push new element first
return newstack
a={b:stack.pop()}
將與每一個新的字典更換a
迭代。要項添加到現有的字典,做
a[b] = stack.pop()
它仍然不起作用 – Oliver 2014-09-29 00:27:03
如果我理解正確的話,儘量
>>> {'b':[1, 2, 3, 4, 5][::-1]}
{'b': [5, 4, 3, 2, 1]} #list inside a dictionary are reversed
相同輸入的兩個錯誤?令人印象深刻! – 2014-09-29 00:31:26
Dictioanry哈希沒有被淘汰。你不能使用字典。你最好直接迭代堆棧...''而不是stack.is_empty():newstack.push(stack.pop())' – ssm 2014-09-29 01:40:40
或者只是使用SonicArg的方法... – ssm 2014-09-29 01:41:50