Skip to content

Instantly share code, notes, and snippets.

@erwinvaneyk
Created October 22, 2013 13:05
Show Gist options
  • Save erwinvaneyk/7100410 to your computer and use it in GitHub Desktop.
Save erwinvaneyk/7100410 to your computer and use it in GitHub Desktop.
A prototype/doodle for a equation generation algorithm.
# Equation Generation Algorithm - prototype script.
import random;
class EquationType:
def __init__(self,pycode,argcount):
self.pycode = pycode;
self.argcount = argcount;
arith = lambda: None
arith.ADD = EquationType("+",2);
arith.SUB = EquationType("-",2);
arith.MUL = EquationType("*",2);
arith.DIV = EquationType("/",2);
arith.POW = EquationType("**",2);
class Equation(object):
result = None;
def __init__(self,type,left="",right=""):
self.type = type; #Equation type
self.left = left;
self.right = right;
def eval(self):
lt = self.left.eval() if type(self.left) == type(self) else self.left;
rt = self.right.eval() if type(self.right) == type(self) else self.right;
self.result = eval(str(lt) + str(self.type.pycode) + str(rt))
return self.result;
def __str__(self):
return "(" + str(self.left) + str(self.type.pycode) + str(self.right) + ")";
@staticmethod
def generate(factorcount,rangeFactors):
assert factorcount >= 2
# generate factors
factors = [];
for k in range(factorcount):
factors.append(random.randint(rangeFactors[0],rangeFactors[1]));
# compose equation
eq = factors.pop();
for k in factors:
operator = random.choice([arith.ADD,arith.SUB,arith.MUL]);
eq = Equation(operator,eq,k) if random.choice([True,False]) else Equation(operator,k,eq);
return eq;
# Test
eq = Equation.generate(3,(0,10));
print (str(eq) + " = " + str(eq.eval()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment