PW_15
Basics
python
from stack import stack
gerard = stack()
gerard.push(1)
gerard.push(2)
gerard.push(4)
print(gerard)
gerard.pop()
gerard.push(3)
print(gerard)
def stackOfList(tab: list) -> stack:
st = stack()
for e in tab:
st.push(e)
return stPositive Stack
I used @overload to have two functions with the same name. I do believe this is not the right syntax, but I can't find the right python docs for that.
python
from typing import overload
from stack import stack
@overload
def positive(tab: list) -> stack:
st = stack()
for e in tab:
if e >= 0:
st.push(e)
return st
@overload
def positive(s: stack) -> stack:
st = stack()
tmp = stack()
while not s.is_empty():
e = s.pop()
tmp.push(e)
while not tmp.is_empty():
e = tmp.pop()
s.push(e)
if e >= 0:
st.push(e)
return st
positive([])
positive(stack())Parentheses
python
from typing import overload
from stack import stack
def parentheses(p : string) -> bool:
st = stack()
for c in p:
if c == "(":
st.push(1)
elif c == ")":
if st.is_empty():
return False
else:
st.pop()
if st.is_empty():
return True
return False
assert parentheses("((()())(()))") == True, "Case True"
assert parentheses("())(()") == False, "Case too soon"
assert parentheses("(())(()") == False, "Case too late"Postfix
python
from stack import stack
def eval_postfix(tab : list) -> float:
st = stack()
r = 0
for e in tab:
print(e)
if e == "+":
while not st.is_empty():
r += st.pop()
elif e == "-":
while not st.is_empty():
r -= st.pop()
elif e == "*":
while not st.is_empty():
r *= st.pop()
elif e == "/":
while not st.is_empty():
r /= st.pop()
else:
st.push(e)
return r
print(eval_postfix([2, 3, '+', 5, '*']))