2 回答
TA贡献1810条经验 获得超4个赞
我希望这会帮助您入门:
operators = ['-', '+', '*', '/']
operands = ['a', 'b', 'c']
# find out all possible combination of operators first. So if you have 3 operands, that would be all permutations of the operators, taken 2 at a time. Also append the same expression operator combinations to the list
from itertools import permutations
operator_combinations = list(permutations(operators, len(operands)-1))
operator_combinations.extend([op]*(len(operands)-1) for op in operators)
# create a list for each possible expression, appending it with an operand and then an operator and so on, finishing off with an operand.
exp = []
for symbols in operator_combinations:
temp = []
for o,s in zip(operands, symbols):
temp.extend([o,s])
temp.append(operands[-1])
exp.append(temp)
for ans in exp:
print(''.join(ans))
输出 :
a-b+c
a-b*c
a-b/c
a+b-c
a+b*c
a+b/c
a*b-c
a*b+c
a*b/c
a/b-c
a/b+c
a/b*c
a-b-c
a+b+c
a*b*c
a/b/c
TA贡献1856条经验 获得超17个赞
这是一个天真的解决方案,它输出所有列的 2 和 3 的组合。
组合列表
使用 operator 包创建一个函数
for循环组合
这可能有重复的列,因此删除重复项
from sklearn.datasets import load_boston
from itertools import combinations
import operator as op
X, y = load_boston(return_X_y=True)
X = pd.DataFrame(X)
comb= list(combinations(X.columns,3))
def operations(x,a,b):
if (x == '+'):
d = op.add(a,b)
if (x == '-'):
d = op.sub(a,b)
if (x == '*'):
d = op.mul(a,b)
if (x == '/'): # divide by 0 error
d = op.truediv(a,(b + 1e-20))
return d
for x in ['*','/','+','-']:
for y in ['*','/','+','-']:
for i in comb:
a = X.iloc[:,i[0]].values
b = X.iloc[:,i[1]].values
c = X.iloc[:,i[2]].values
d = operations(x,a,b)
e = operations(y,d,c)
X[f'{i[0]}{x}{i[1]}{y}{i[2]}'] = e
X[f'{i[0]}{x}{i[1]}'] = d
X = X.loc[:,~X.columns.duplicated()]
添加回答
举报
