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) 
5

3 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 
0

Simpler one:

def peek_stack(stack): if stack: return stack[-1] 
1
def peek(stk): if stk == []: return None else: top = len(stk) - 1 return stk[top] 
5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy