[Tutor] html checker
eryksun
eryksun at gmail.com
Tue Oct 2 03:14:40 CEST 2012
On Mon, Oct 1, 2012 at 7:46 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> 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
It's a good example, but please indicate when you've switched to
pseudocode. In Python "stack = []" assigns a new list to stack, which
has no "push" method. It can append() and pop() from the end in
constant time to implement an efficient stack.
More information about the Tutor
mailing list