Last active
August 29, 2015 13:56
-
-
Save AndrewHanes/9058635 to your computer and use it in GitHub Desktop.
Prefix Equation Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python | |
from random import * | |
import sys | |
""" | |
Generate a prefix expr of maxlength l | |
""" | |
def generateExpression(l): | |
funcs = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b} | |
isInt = random() | |
if(l == 0): | |
n = int(random() * 100) | |
return str(n), n | |
else: | |
ind = int(random() * len(funcs.keys())) | |
op = funcs.keys()[ind] | |
left = generateExpression(l-1) | |
right = generateExpression(l-1) | |
return op + " " + left[0] + " " + right[0], funcs[op](left[1],right[1]) | |
def printExpr(exp): | |
if exp[1] < sys.maxint and exp[1] > -1*sys.maxint-1: | |
print x[0] | |
print x[1] | |
MAXLEN = 2 | |
for i in range(100): | |
x = (generateExpression(int(random()*MAXLEN))) | |
printExpr(x) | |
MAXLEN = 3 | |
for i in range(100): | |
x = (generateExpression(int(random()*MAXLEN))) | |
printExpr(x) | |
MAXLEN = 4 | |
for i in range(100): | |
x = (generateExpression(int(random()*MAXLEN))) | |
printExpr(x) | |
print('\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should probably change the shebang to something like
#!/usr/bin/env python
. That way it works if they don't have python installed to/usr/bin
.