expressionTree.py 1.43 KB
Newer Older
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Equation Tree class
# AI Final Project
# Takes an equation of the form x + 3 = 5 + x and makes this into an equation tree
# this means = is in root and each expression is a tree on either side
# currently only works for addition and two variables on each side of equation

class EquationTreeNode:
	def __init__(self, value, parent=None):
		self.value = value
		self.left = None
		self.right = None
		self.parent = parent

	def setLeft(self, newNode):
		self.left = newNode

	def setRight(self, newNode):
		self.right = newNode

	def addLeftNode(self, newNode):
		self.left = newNode
		newNode.parent = self

	def addRightNode(self, newNode):
		self.right = newNode
		newNode.parent = self

	def splitExpression(self, expression):
		expressions = expression.split("+")
		leftNode = EquationTreeNode(expressions[0])
		rightNode = EquationTreeNode(expressions[1])
		self.addLeftNode(leftNode)
		self.addRightNode(rightNode)

'''def main():
	equation = "3x+5=2+2x"
	expressions = equation.split("=")
	rootNode = EquationTreeNode("=", None)
	
	leftNode = EquationTreeNode("+")
	rootNode.addLeftNode(leftNode)
	splitExpression(expressions[0], leftNode)
	
	rightNode = EquationTreeNode("+")
	rootNode.addRightNode(rightNode)
	splitExpression(expressions[1], rightNode)


	print(rootNode.value)
	print(rootNode.left.value, rootNode.right.value)
	print(rootNode.left.left.value, rootNode.left.right.value, rootNode.right.left.value, rootNode.right.right.value)


main()	'''