Commit 1e7de1fe authored by mrk022's avatar mrk022

updated progress

parent 9ad86f45
# queue code from http://knuth.luther.edu/~leekent/CS2Plus/chap4/chap4.html
class Queue:
def __init__(self):
self.items = []
self.frontIdx = 0
def __compress(self):
newitems = []
for i in range(self.frontIdx,len(self.items)):
newitems.append(self.items[i])
self.items = newitems
self.frontIdx = 0
def dequeue(self):
if self.isEmpty():
raise RuntimeError("Attempt to dequeue an empty queue")
# When queue is half full, compress it. This
# achieves an amortized complexity of O(1) while
# not letting the list continue to grow unchecked.
if self.frontIdx * 2 > len(self.items):
self.__compress()
item = self.items[self.frontIdx]
self.frontIdx += 1
return item
def enqueue(self,item):
self.items.append(item)
def front(self):
if self.isEmpty():
raise RuntimeError("Attempt to access front of empty queue")
return self.items[self.frontIdx]
def isEmpty(self):
return self.frontIdx == len(self.items)
def clear(self):
self.items = []
self.frontIdx = 0
def main():
q = Queue()
items = list(range(10))
items2 = []
for k in items:
q.enqueue(k)
if q.front() == 0:
print("Test 1 Passed")
else:
print("Test 1 Failed")
while not q.isEmpty():
items2.append(q.dequeue())
if items2 != items:
print("Test 2 Failed")
else:
print("Test 2 Passed")
for k in items:
q.enqueue(k)
items2 = []
while not q.isEmpty():
items2.append(q.dequeue())
if items2 != items:
print("Test 3 Failed")
else:
print("Test 3 Passed")
try:
q.dequeue()
print("Test 4 Failed")
except RuntimeError:
print("Test 4 Passed")
except:
print("Test 4 Failed")
try:
q.front()
print("Test 5 Failed")
except RuntimeError:
print("Test 5 Passed")
except:
print("Test 5 Failed")
if __name__=="__main__":
main()
\ No newline at end of file
File added
# base tree code from http://knuth.luther.edu/~leekent/CS2Plus/chap6/chap6.html
# changed this code to allow for variable functions, and change infix expressions to postfix
import queue
class TimesNode:
def __init__(self, left, right):
self.left = left
self.right = right
def eval(self):
return self.left.eval() * self.right.eval()
def inorder(self):
return "(" + self.left.inorder() + " * " + self.right.inorder() + ")"
class PlusNode:
def __init__(self, left, right):
self.left = left
self.right = right
def eval(self):
return self.left.eval() + self.right.eval()
def inorder(self):
return "(" + self.left.inorder() + " + " + self.right.inorder() + ")"
class MinusNode:
def __init__(self,left, right):
self.left = left
self.right = right
def eval(self):
return self.left.eval() - self.right.eval()
def inorder(self):
return "(" + self.left.inorder() + "-" + self.right.inorder() + ")"
class NumNode:
def __init__(self, num):
self.num = num
def eval(self):
return self.num
def inorder(self):
return str(self.num)
def check_if_variables(x, y):
if 'x' in x and 'x' in y:
return "both_vars"
elif 'x' in x or 'x' in y:
return "one_var"
else:
return "both_const"
def E(q):
if q.isEmpty():
raise ValueError("Invalid Prefix Expression")
token = q.dequeue()
if token == "+":
return PlusNode(E(q),E(q))
if token == "*":
return TimesNode(E(q),E(q))
if token == "-":
return MinusNode(E(q), E(q))
try:
output = NumNode(float(token))
except:
print("Not a valid operation, need variables of like terms")
output = NumNode(float(0))
return output
OPERATORS = set(['+', '-', '*', '/', '(', ')'])
PRIORITY = {'+':1, '-':1, '*':2, '/':2}
def infix_to_prefix(formula):
op_stack = []
exp_stack = []
for ch in formula.split():
if not ch in OPERATORS:
exp_stack.append(ch)
elif ch == '(':
op_stack.append(ch)
elif ch == ')':
while op_stack[-1] != '(':
op = op_stack.pop()
a = exp_stack.pop()
b = exp_stack.pop()
exp_stack.append( op+b+a )
op_stack.pop() # pop '('
else:
while op_stack and op_stack[-1] != '(' and PRIORITY[ch] <= PRIORITY[op_stack[-1]]:
op = op_stack.pop()
a = exp_stack.pop()
b = exp_stack.pop()
exp_stack.append( op+" "+b+" "+a )
op_stack.append(ch)
# leftover
while op_stack:
op = op_stack.pop()
a = exp_stack.pop()
b = exp_stack.pop()
exp_stack.append( op+" "+b+" "+a )
print exp_stack[-1]
return exp_stack[-1]
def eval_tree(expression):
x = NumNode(5)
y = NumNode(4)
p = PlusNode(x,y)
t = TimesNode(p, NumNode(6))
root = PlusNode(t, NumNode(3))
print(root.eval())
print(root.inorder())
#x = input("Please enter a prefix expression: ")
x = infix_to_prefix(expression)
lst = x.split()
q = queue.Queue()
for token in lst:
q.enqueue(token)
root = E(q)
print(root.eval())
print(root.inorder())
#print(infix_to_prefix("3 + 4 - 6"))
def split_equation(equation):
expressions = equation.split("=")
return expressions
def main():
exp = split_equation("3 * 4 - 6=0")
eval_tree(exp[0])
if __name__ == "__main__":
main()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment