UNARIES = ["-%s", "e(%s)", "arctan(%s)"] BINARIES = ["%s + %s", "%s - %s", "%s * %s", "%s / %s", "%s ^ %s"] PROB_PARENTHESES = 0.3 PROB_BINARY = 0.8 def generate_expressions(scope, num_exp, num_ops): scope = list(scope) for _ in range(num_ops): if random() < PROB_BINARY: op = choice(BINARIES) args = None while not args or ('/' in op and args[1] == '0'): args = (choice(scope), choice(scope)) ex = op % args if random() < PROB_PARENTHESES: ex = "(%s)" % ex scope.append(ex) else: scope.append(choice(UNARIES) % choice(scope)) return scope[-num_exp:] for x in generate_expressions(["0", "1", "2", "10", "100", "x"], 1000, 100): print('"' + x + '"') for x in generate_expressions(["0", "1", "2", "10", "100", "x"], 100, 100): pprint(parse('diff(' + x + ', x)'))