Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peek stack in python 3

Tags:

python

Question: Implement peek(stack) that returns, but doesn't remove, the top element from a stack. Return None if list is empty.

I tried many times but did not successfully get it, anyone can help?

My attempt:

def peek_stack(stack):
    if stack == []:
        return None
    else:
        s= stack.copy()
        return s.pop(0)
like image 689
Chin Huat Avatar asked Oct 18 '17 02:10

Chin Huat


People also ask

How do you peek a stack in Python?

peek() – Return the top item in the stack. If the stack is empty, raise an exception. push(value) – Push a value into the head of the stack. pop() – Remove and return a value in the head of the stack.

Is there a peek () in Python?

Peek function in queueA peek function in the python queue is used to print the first element of the queue. It returns the item which is present at the front index of the queue. It will not remove the first element but print it.

What is peek () in stack?

Stack. peek() method in Java is used to retrieve or fetch the first element of the Stack or the element present at the top of the Stack. The element retrieved does not get deleted or removed from the Stack. Syntax: STACK.peek()

What is a [- 1 in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.


1 Answers

If you need to use your way to solve this, please use return s.pop() rather than return s.pop(0), because s.pop() will pop up the last element, but s.pop(0) will pop up the first element...

And by the way, it's recommend just implement it like this(it can avoid copy your stack, and improve performance)

def peek_stack(stack):
    if stack:
        return stack[-1]    # this will get the last element of stack
    else:
        return None
like image 69
Ballack Avatar answered Sep 23 '22 01:09

Ballack