gpt4 book ai didi

Python - 所有组合包括括号

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:58 24 4
gpt4 key购买 nike

For u unknown variables (e.g. a,b,c,d) and the symbols +-*/, find all possible equations of length n

An example being (for u=2, n=5):

(a+b)/a

我当前的代码可以创建所有可能方程的列表,但没有括号

v = ["a", "b"]            #Variables
s = ["+", "-", "*", "-"] #Symbols
n = 7 #Amount of variables and symbols
a = [] #Lists combined (find possible equations from)
for i in range(n):
if i % 2 == 0:
a.append(v)
else:
a.append(s)
equations = list(itertools.product(*a))
for each in equations:
print("".join(each))

总之,我编写的代码不包含方程式的所有可能性。

例如对于 n=5 和 2 个变量,我的代码找不到 (a+b)*b 的可能性

对于 n=7 和 4 个变量,它找不到 `(a+b)*(c+d)

我的主要问题:我如何创建一些代码来获取每个可能的方程式并找到所有可能的括号而不重复

一个重复的例子:(a+b)*ca*(b+c)

注意:这是重复的,因为每个可能的方程都被测试了,在某些时候 a+b 会变成 b+c,所以 *c 会变成 *a

最佳答案

这个可以工作,但它确实有很多表达式会产生相同的东西,例如 x-xx/x 有许多不同的地方x。然而,由于结合性或交换性,它避免了琐碎的重复。

所有可能的表达式列表也很快变得非常长。例如,对于 4 个变量和所有具有 5 个项的表达式,您将得到 7845320 个。使用生成器可以避免内存不足,但不会导致运行时间过长。

def all_expressions(size, variables):
def _all_expressions(_size):
if _size == 1:
for variable in variables:
yield (variable, '')
else:
for subsize in range(1, _size//2 + 1):
for expr1, type1 in _all_expressions(subsize):
for expr2, type2 in _all_expressions(_size - subsize):
if subsize < _size - subsize or expr1 <= expr2:
if type1 == '+':
if type2 != '+':
yield ("({} + {})".format(expr2, expr1), '+')
else:
yield ("({} + {})".format(expr1, expr2), '+')
if type1 == '*':
if type2 != '*':
yield ("({} * {})".format(expr2, expr1), '*')
else:
yield ("({} * {})".format(expr1, expr2), '*')
if type1 != '*':
yield ("({} / {})".format(expr1, expr2), '/')
if type1 != '+':
yield ("({} - {})".format(expr1, expr2), '-')
if subsize < _size - subsize:
if type2 != '*':
yield ("({} / {})".format(expr2, expr1), '/')
if type2 != '+':
yield ("({} - {})".format(expr2, expr1), '-')
for expr, t in _all_expressions(size):
yield expr

for expr in all_expressions(3, ['a', 'b', 'c']):
print(expr)

关于Python - 所有组合包括括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54656807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com