有没有办法自动生成有效的算术表达式?

Edw*_*win 7 python parsing

我目前正在尝试创建一个Python脚本,它将自动生成有效的空格分隔的算术表达式.但是,我得到的示例输出如下所示:( 32 - 42 / 95 + 24 ( ) ( 53 ) + ) 21

虽然我的空括号完全没问题,但我不能在计算中使用这个自动生成的表达式,因为24和53之间没有运算符,而结束时21之前的+没有第二个参数.

我想知道的是,有没有办法使用Pythonic解决方案解释/修复这些错误?(在任何人指出它之前,我将首先承认我下面发布的代码可能是我推动的最差代码并且符合......嗯,很少有Python的核心原则.)

import random
parentheses = ['(',')']
ops = ['+','-','*','/'] + parentheses

lines = 0

while lines < 1000:
    fname = open('test.txt','a')
    expr = []
    numExpr = lines
    if (numExpr % 2 == 0):
        numExpr += 1
    isDiv = False # Boolean var, makes sure there's no Div by 0

    # isNumber, isParentheses, isOp determine whether next element is a number, parentheses, or operator, respectively
    isNumber = random.randint(0,1) == 0 # determines whether to start sequence with number or parentheses
    isParentheses = not isNumber
    isOp = False
    # Counts parentheses to ensure parentheses are matching
    numParentheses = 0
    while (numExpr > 0 or numParentheses > 0):
        if (numExpr < 0 and numParentheses > 0):
            isDiv = False
            expr.append(')')
            numParentheses -= 1
        elif (isOp and numParentheses > 0):
            rand = random.randint(0,5)
            expr.append(ops[rand])
            isDiv = (rand == 3) # True if div op was just appended
            # Checks to see if ')' was appended
            if (rand == 5):
                isNumber = False
                isOp = True
                numParentheses -= 1
            # Checks to see if '(' was appended
            elif (rand == 4):
                isNumber = True
                isOp = False
                numParentheses += 1
            # All other operations go here
            else:
                isNumber = True
                isOp = False
        # Didn't add parentheses possibility here in case expression in parentheses somehow reaches 0
        elif (isNumber and isDiv):
            expr.append(str(random.randint(1,100)))
            isDiv = False
            isNumber = False
            isOp = True
        # If a number's up, decides whether to append parentheses or a number
        elif (isNumber):
            rand = random.randint(0,1)
            if (rand == 0):
                expr.append(str(random.randint(0,100)))
                isNumber = False
                isOp = True
            elif (rand == 1):
                if (numParentheses == 0):
                    expr.append('(')
                    numParentheses += 1
                else:
                    rand = random.randint(0,1)
                    expr.append(parentheses[rand])
                    if rand == 0:
                        numParentheses += 1
                    else:
                        numParentheses -= 1
            isDiv = False
        numExpr -= 1

    fname.write(' '.join(expr) + '\n')
    fname.close()
    lines += 1
Run Code Online (Sandbox Code Playgroud)

Ray*_*oal 15

是的,您可以以Pythonic方式生成随机算术表达式.但是,你需要改变你的方法.不要试图生成一个字符串并计算parens.而是生成随机表达式树,然后输出.

通过表达式目录树,我的意思是叫,比如类,实例Expression与子类Number,PlusExpression,MinusExpression , 'TimesExpression,DivideExpressionParenthesizedExpression.除了Number将具有类型的字段之外,其中每一个都是Expression.给每个人一个合适的__str__方法.生成一些随机表达式对象,然后打印"root".

你能从这里拿走它还是要我编码?

附录:一些示例入门代码.不生成随机表达式(但?)但可以添加....

# This is just the very beginning of a script that can be used to process
# arithmetic expressions.  At the moment it just defines a few classes
# and prints a couple example expressions.

# Possible additions include methods to evaluate expressions and generate
# some random expressions.

class Expression:
    pass

class Number(Expression):
    def __init__(self, num):
        self.num = num

    def __str__(self):
        return str(self.num)

class BinaryExpression(Expression):
    def __init__(self, left, op, right):
        self.left = left
        self.op = op
        self.right = right

    def __str__(self):
        return str(self.left) + " " + self.op + " "  + str(self.right)

class ParenthesizedExpression(Expression):
    def __init__(self, exp):
        self.exp = exp

    def __str__(self):
        return "(" + str(self.exp) + ")"

e1 = Number(5)
print e1

e2 = BinaryExpression(Number(8), "+", ParenthesizedExpression(BinaryExpression(Number(7), "*", e1)))
print e2
Run Code Online (Sandbox Code Playgroud)

**ADDENDUM 2**

回到Python非常有趣.我无法抗拒实现随机表达式生成器.它建立在上面的代码之上.抱怨HARDCODING !!

from random import random, randint, choice

def randomExpression(prob):
    p = random()
    if p > prob:
        return Number(randint(1, 100))
    elif randint(0, 1) == 0:
        return ParenthesizedExpression(randomExpression(prob / 1.2))
    else:
        left = randomExpression(prob / 1.2)
        op = choice(["+", "-", "*", "/"])
        right = randomExpression(prob / 1.2)
        return BinaryExpression(left, op, right)

for i in range(10):
    print(randomExpression(1))
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

(23)
86 + 84 + 87 / (96 - 46) / 59
((((49)))) + ((46))
76 + 18 + 4 - (98) - 7 / 15
(((73)))
(55) - (54) * 55 + 92 - 13 - ((36))
(78) - (7 / 56 * 33)
(81) - 18 * (((8)) * 59 - 14)
(((89)))
(59)
Run Code Online (Sandbox Code Playgroud)

不是太漂亮了.我认为它让太多的父母.也许改变括号表达式和二进制表达式之间选择的概率可能会很好....


Dr.*_*. V 5

我发现这个线程有类似的任务,即生成用于符号计算的单元测试的随机表达式。在我的版本中,我包含一元函数并允许符号是任意字符串,即您可以使用数字或变量名称。

from random import random, choice

UNARIES = ["sqrt(%s)", "exp(%s)", "log(%s)", "sin(%s)", "cos(%s)", "tan(%s)",
           "sinh(%s)", "cosh(%s)", "tanh(%s)", "asin(%s)", "acos(%s)",
           "atan(%s)", "-%s"]
BINARIES = ["%s + %s", "%s - %s", "%s * %s", "%s / %s", "%s ** %s"]

PROP_PARANTHESIS = 0.3
PROP_BINARY = 0.7

def generate_expressions(scope, num_exp, num_ops):
    scope = list(scope) # make a copy first, append as we go
    for _ in xrange(num_ops):
        if random() < PROP_BINARY: # decide unary or binary operator
            ex = choice(BINARIES) % (choice(scope), choice(scope))
            if random() < PROP_PARANTHESIS:
                ex = "(%s)" % ex
            scope.append(ex)
        else:
            scope.append(choice(UNARIES) % choice(scope))
    return scope[-num_exp:] # return most recent expressions
Run Code Online (Sandbox Code Playgroud)

正如从以前的答案中复制的那样,我只是在二元运算符周围加上一些括号PROP_PARANTHESIS(这有点作弊)。二元运算符比一元运算符更常见,因此我也将其留作配置 ( PROP_BINARY)。示例代码是:

scope = [c for c in "abcde"]
for expression in generate_expressions(scope, 10, 50):
    print expression
Run Code Online (Sandbox Code Playgroud)

这将生成类似以下内容的内容:

e / acos(tan(a)) / a * acos(tan(a)) ** (acos(tan(a)) / a + a) + (d ** b + a)
(a + (a ** sqrt(e)))
acos((b / acos(tan(a)) / a + d) / (a ** sqrt(e)) * (a ** sinh(b) / b))
sin(atan(acos(tan(a)) ** (acos(tan(a)) / a + a) + (d ** b + a)))
sin((b / acos(tan(a)) / a + d)) / (a ** sinh(b) / b)
exp(acos(tan(a)) / a + acos(e))
tan((b / acos(tan(a)) / a + d))
acos(tan(a)) / a * acos(tan(a)) ** (acos(tan(a)) / a + a) + (d ** b + a) + cos(sqrt(e))
(acos(tan(a)) / a + acos(e) * a + e)
((b / acos(tan(a)) / a + d) - cos(sqrt(e))) + sinh(b)
Run Code Online (Sandbox Code Playgroud)

放置PROP_BINARY = 1.0和应用

scope = range(100)
Run Code Online (Sandbox Code Playgroud)

让我们回到输出

43 * (50 * 83)
34 / (29 / 24)
66 / 47 - 52
((88 ** 38) ** 40)
34 / (29 / 24) - 27
(16 + 36 ** 29)
55 ** 95
70 + 28
6 * 32
(52 * 2 ** 37)
Run Code Online (Sandbox Code Playgroud)