On 01/10/12 20:59, Matthew Dalrymple wrote:

i don't really understand the pop and push or even stacks for that
matter...the professor i have isn't really the best at teaching...so if
anyone could give me a hand with any of this that would be appreciated

The Raw materials topic in my tutor has a short intro to stacks. It says, in part:
----------------
Stack

Think of a stack of trays in a restaurant. A member of staff puts a pile of clean trays on top and these are removed one by one by customers. The trays at the bottom of the stack get used last (and least!). Data stacks work the same way: you push an item onto the stack or pop one off. The item popped is always the last one pushed. This property of stacks is sometimes called Last In First Out or LIFO. One useful property of stacks is that you can reverse a list of items by pushing the list onto the stack then popping it off again. The result will be the reverse of the starting list. Stacks are not built in to Python, VBScript or JavaScript. You have to write some program code to implement the behavior. Lists are usually the best starting point since like stacks they can grow as needed.
-----------------

As c smith points out, Python lists have a pop/push mechanism as standard which makes implementing a stack in Python fairly trivial.

To expand on how reversing works consider pushing the string foo onto the stack then popping it off again:

s = 'foo'
stack = []
stack.push(s[0])  # stack -> ['f']
stack.push(s[1])  # stack -> ['o','f']
stack.push(s[2])  # stack -> ['o','o','f']

c1 = stack.pop()  # stack -> ['o','f'], c1 = 'o'
c2 = stack.pop()  # stack -> ['f'], c1 = 'o', c2 = 'o'
c3 = stack.pop()  # stack -> [], c1 = 'o', c2 = 'o', c3 = 'f'

print c1+c2+c3  # prints 'oof' the reverse of s

HTH,

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to