Reputation: 323
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])
I think this should work but it doesn't, Key error and empty stack errors are raised
Upvotes: 0
Views: 70
Reputation: 458
If I correctly understood, try
>>> {'b':[1, 2, 3, 4, 5][::-1]}
{'b': [5, 4, 3, 2, 1]} #list inside a dictionary are reversed
Upvotes: 0
Reputation: 517
For reversing a stack, you can consider the stack as a list and do:
stack.reverse()
instead of popping and pushing in a spare stack. From Python 2 documentation:
Reverse the elements of the list, in place
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
EDIT: As rephrased by the questioner, if you want to reverse a stack into a new one, you can do:
def reverse_and_return(stack):
newstack = [] # New list/stack
for element in stack:
newstack.insert(0, element) # Push new element first
return newstack
Upvotes: 1
Reputation: 362187
a={b:stack.pop()}
That will replace a
with a new dictionary each iteration. To add keys to the existing dictionary, do
a[b] = stack.pop()
Upvotes: 0