Skip to content

Instantly share code, notes, and snippets.

@velnias75
Last active February 18, 2016 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velnias75/9fabac7d88cd9fe69d1a to your computer and use it in GitHub Desktop.
Save velnias75/9fabac7d88cd9fe69d1a to your computer and use it in GitHub Desktop.
Python script to create random (huge) expressions
#!/usr/bin/env python
#
# Copyright (C) 2016 Heiko Schaefer <heiko@rangun.de>
#
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
#
import ast
import sys
import random
import itertools
import operator as op
def gen_digit(n):
digit = ""
if random.randint(0, 1e06) % 17 == 0: digit += "-"
return digit + str(random.randint(pow(10, n - 1), pow(10, n) - 1));
def rnd_op():
ops = [ "+", "-", "*", "/" ]
return ops[random.randint(0, 3)]
def eval_(node):
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Mod: op.mod, ast.USub: op.neg}
if isinstance(node, ast.Num): return node.n
elif isinstance(node, ast.BinOp):
return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp):
return operators[type(node.op)](eval_(node.operand))
else: raise TypeError(node)
def right_op(op, expr):
if op == "/":
try: v = eval_(ast.parse(expr, mode='eval').body)
except ZeroDivisionError: v = 0
if v == 0: return op + " (" + expr + " + " + gen_digit(random.randint(1, 4)) + ")"
return op + " " + expr
def gen_term():
term = ""
if random.randint(0, 1e06) % 17 == 0: term += "-"
return term + "(" + right_op(gen_digit(random.randint(1, 4)), \
right_op(rnd_op() + " " + gen_digit(random.randint(1, 4)), \
rnd_op() + " " + gen_digit(random.randint(1, 4)))) + ")"
def build_expr(): return "(" + gen_term() + " " + right_op(rnd_op(), gen_term()) + \
" " + right_op(rnd_op(), gen_term()) + ")"
def rnd_expr(m):
sys.stdout.write(build_expr())
sys.stdout.flush()
for _ in itertools.repeat(None, m):
sys.stdout.write(" " + right_op(rnd_op(), build_expr()))
sys.stdout.flush()
sys.stdout.write("\n")
sys.stdout.flush()
if len(sys.argv) > 1: rnd_expr(int(sys.argv[1]))
else: rnd_expr(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment