MCS 260 Fall 2021
Emily Dumas
import os
fn = os.path.join("data","pride.txt")
Now fn
is "data\\pride.txt"
if running on Windows, or "data/pride.txt"
on MacOS or Linux.
os.path.exists(fn)
returns a boolean to indicate whether a file with the given name exists already.
More on this module later!
Adding an item is called push, removing an item is called pop.
Often used for:
You can make a stack using a Python list:
list.append
list.pop
Adding an item is called enqueue. Removing an item is called dequeue.
Common applications:
Maybe do this with a list?
list.append(item)
list.pop(0)
Using a list as a queue is NOT efficient.
Removing an item from the beginning of a list takes time proportional to list size.
More efficient: deque from the collections module
import collections
Q = collections.deque() # pronounced "deck"
Q.append("first in") # enqueue
Q.append(260)
Q.append("last in")
while len(Q)>0:
x = Q.popleft() # dequeue
print(x)
Output:
first in
260
last in
Notice deque implements queue operations:
deque.append(item)
deque.popleft()
Efficiency means time to add or remove an item is independent of how many items are present (like stacks).
Checking parenthesis matching (example of parsing)
This expression is ok:
((2+3) - (4*5))
These are not:
((5*7))) - ((2)
((2+3)-5))
Goal: Decide if ok, give useful error if not.
parens.py
"""Check arithmetic expression for balanced parentheses"""
print("Enter an arithmetic expression in parentheses:")
s = input().strip()
paren_stack = []
for i,c in enumerate(s):
if c == "(":
paren_stack.append(i)
elif c == ")":
if len(paren_stack) == 0:
# Too many right parentheses
print("ERROR: Extra right parenthesis")
print(s)
print(i*" " + "^")
break
paren_stack.pop()
if len(paren_stack) > 0:
# Unclosed left parenthesis
i = paren_stack.pop() # Where was the left paren that's open?
print("ERROR: Unclosed parenthesis")
print(s)
print(i*" " + "^")