forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_min.py
More file actions
30 lines (26 loc) · 728 Bytes
/
remove_min.py
File metadata and controls
30 lines (26 loc) · 728 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
"""
Given a stack, a function remove_min accepts a stack as a parameter
and removes the smallest value from the stack.
For example:
bottom [2, 8, 3, -6, 7, 3] top
After remove_min(stack):
bottom [2, 8, 3, 7, 3] top
"""
def remove_min(stack):
storage_stack = []
if len(stack) == 0: # Stack is empty
return stack
# Find the smallest value
min = stack.pop()
stack.append(min)
for i in range(len(stack)):
val = stack.pop()
if val <= min:
min = val
storage_stack.append(val)
# Back up stack and remove min value
for i in range(len(storage_stack)):
val = storage_stack.pop()
if val != min:
stack.append(val)
return stack