Reputation: 31
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()
Upvotes: 0
Views: 122
Reputation: 1185
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=' ')
Upvotes: 0
Reputation: 1267
Try something like this:
def view():
print(list(reversed(stack)))
to create reversed copy of your list and print it out.
Upvotes: 1