0

i've got the code working but I've written my code in python implementing a stack, it is pushing and popping following LIFO but when you view the list it prints it as:

1 
2 
3 

showing the last item which is 3 at the bottom, how can I make it show the last item at the top like a proper stack?

my code is as follows:

stack_pointer = 0
stack =[]
max_length = 2


def view():
        for x in range (len(stack)):
            print(stack[x])
def push():
    global stack_pointer
    if len (stack)> max_length:
        print("Maximum stack length reached!") 
    else:
        stack_pointer = stack_pointer + 1
        item = input("Please enter the  item you wishto add to the stack: ")
        stack.append(item)

def pop():
    global stack_pointer
    if len (stack)<= 0:
        print ("stack is empty!")
    else:
        item = stack.pop
        stack_pointer = stack_pointer - 1
        print ("you just popped out: ", item)

while True:
    print ("")
    print("Python implementation of a stack")
    print("********************************")
    print("1. view Stack")
    print("2. Push onto Stack")
    print("3. Pop out of Stack")
    print("********************************")
    print("")
    menu_choice = int (input("Please enter your menu choice: "))
    print ("")
    print ("")

    if menu_choice == 1:
        view()
    elif menu_choice == 2:
        push()
    elif menu_choice == 3:
        pop()
lisa turner
  • 31
  • 1
  • 5
  • Aside: Your stack pop looks broken; `item = stack.pop` is setting item to hold the address of the method, you need `item = stack.pop()` to call the pop method and set item to hold the value popped from the stack. – TessellatingHeckler Jan 15 '16 at 01:08

2 Answers2

1

Try something like this:

def view():
    print(list(reversed(stack)))

to create reversed copy of your list and print it out.

dizballanze
  • 1,267
  • 8
  • 18
0

This should work: a start of the stack's length - 1 , a stop of -1, and step of -1; no new lists are created or any extra operations, only a modification of the range object parameters, thus it's efficient:

def view():
    for x in range (len(stack) - 1, -1, -1):
        print(stack[x])  # or print(stack[x], end=' ')
SoreDakeNoKoto
  • 1,175
  • 1
  • 9
  • 16
  • thanks @brianho your suggestion works but i don't understand the code. please can you explain this further." this should work: a start of the stack's length - 1 , a stop of -1, and step of -1; no new lists are created or any extra operations, only a modification of the range object parameters, thus it's efficient". – lisa turner Jan 15 '16 at 23:54
  • When you use 'range' like in a for loop, you are basically creating a 'range' object, which takes 3 parameters at creation. A start value, (default is 0), a stop value (must be indicated) and a step value (default is 1), which is always added to the current value to obtain the next value in the series. So when u say range(100), since u passed only one parameter, Python assumes this parameter is the mandatory argument i.e. the stop value, and then uses the default values of start and stop. So what you really have is range(0,100,1). Now when this object is created and is used in a for loop like: – SoreDakeNoKoto Jan 16 '16 at 00:04
  • E.g. for i in range(100)...all the 100 values in this range (0-99) are not created at once in memory; that would be most wasteful. Instead, the range object keeps track of its current value in every iteration and when a new iteration begins, it simply adds the 'step' value to it, continuing this till it hits the 'stop' value. E.g. In range(3,100,2), the first number (also the current value) would be 3; during the next iteration, the current value would be updated to become 3+2=5, and the next would be 5+2=7, and so on. No list is created, just basic arithmetic each loop. – SoreDakeNoKoto Jan 16 '16 at 00:12
  • Now looking at your case, consider that your stack has 5 items in it. When you use a start of 'len(stack) - 1', it means the first value will be 4. Considering that you want the stack to print the list starting from the last member, it makes sense that the first value printed should be stack[4]. But, unlike before, we want the values returned by the range object to be in decreasing order down to 0, the index of the stacks first element. In order to do this, we use a NEGATIVE step; since the step is always ADDED to the current value, this will work. If the first value yielded is 5, the next – SoreDakeNoKoto Jan 16 '16 at 00:18
  • Will be 5+(-1)=4, the next will be 4+(-1)=3, and so on. Also remember that we want to stop at an index of 0. So we simply change the stop argument to -1, since python always stops right before it gets to the 'stop' value. So you can now see how this object begins at 5,4,3....1,0 and then ends. The range object is efficient because iterating over numbers from 0-10 uses about the same space as iterating from 0-1000000. In both cases, all the numbers are never generated at once, only the current value is updated every iteration. Calling the 'reversed' function, however, involves: – SoreDakeNoKoto Jan 16 '16 at 00:25
  • It is efficient since all it returns is an iterator, that yields a value during every iteration, not unlike the range object. Calling 'list()' on the iterator, however, involves the creation of a new list. As the number of elements in your stack grows, so will the time taken to create a new list and load all those elements into memory. Thus you can use my method or you could try 'for i in reversed(stack): print(i)'. This is still efficient, since it runs in constant time, irrespective of the number of elements in your stack. Hope its all clear :) – SoreDakeNoKoto Jan 16 '16 at 00:47