假设我有三个整数。我想获取所有可能值的列表,这些值是通过在它们之间执行所有16(4 *, /, +, -
的4x4)次操作获得的。
[就像我有3 4 1
,我们应该得到值1,2,6,7,7,8,9,11,12,13、15和16。也就是说,>
res = num1 (op1) num2 (op2) num3
,其中的运算符是:
["**", "*/", "*+", "*-", "/*", "//", "/+", "/-", "+*", "+/", "++", "+-", "-*", "-/", "-+", "--"]
。但是,要注意的是,只有
,即除数是红利的因子,才能进行除法。x%y==0
到目前为止,我已经能够蛮力地执行每个操作,但是缺少一些答案。我还定义了一个自定义的除法运算以考虑catch in account
我需要返回一个列表,其中包含全为正的唯一值。
我当前的代码是一团糟,但在这里只是为了解决这个问题。这也缺少一些值。
def div(x, y): if x!=0 and y!=0: if x%y==0:return x/y else:return None ops_lis = ["**", "*/", "*+", "*-", "/*", "//", "/+", "/-", "+*", "+/", "++", "+-", "-*", "-/", "-+", "--"] d1, d2, d3 = map(int, input().split()) cal_lis, res_lis = [], [] for op in ops_lis: if op[0] == "*" and op[1] == "*":cal_lis.append(d1*d2*d3) if op[0] == "*" and op[1] == "/": if div(d1*d2, d3) != None:cal_lis.append(div(d1*d2, d3)) cal_lis.append(div(d1*d2, d3)) if op[0] == "*" and op[1] == "+": cal_lis.append(d1*(d2+d3)) cal_lis.append((d1*d2)+d3) if op[0] == "*" and op[1] == "-": cal_lis.append(d1*d2-d3) cal_lis.append(d1*(d2-d3)) cal_lis.append((d1*d3)-d2) if op[0] == "/" and op[1] == "*":cal_lis.append(div(d1, d2*d3)) if op[0] == "/" and op[1] == "/": if div(d1, d2) == None or div(d2, d3) == None: cal_lis.append(None) else: cal_lis.append(div(div(d1, d2), d3)) if op[0] == "/" and op[1] == "+": if div(d1, d2) == None: cal_lis.append(None) else: cal_lis.append(div(d1, d2)+d3) if op[0] == "/" and op[1] == "-": if div(d1, d2) == None: cal_lis.append(None) else: cal_lis.append(div(d1, d2)-d3) if op[0] == "+" and op[1] == "*": cal_lis.append(d1+d2*d3) cal_lis.append((d1+d2)*d3) cal_lis.append((d1+d3)*d2) if op[0] == "+" and op[1] == "/": if div(d2, d3) == None: cal_lis.append(None) else: cal_lis.append(d1+div(d2, d3)) if op[0] == "+" and op[1] == "+":cal_lis.append(d1+d2+d3) if op[0] == "+" and op[1] == "-":cal_lis.append(d1+d2-d3) if op[0] == "-" and op[1] == "*": cal_lis.append(d1-d2*d3) cal_lis.append((d1-d2)*d3) cal_lis.append((d1-d3)*d2) if op[0] == "-" and op[1] == "/": if div(d2, d3) == None:cal_lis.append(None) else: cal_lis.append(d1-div(d2, d3)) if div(d1-d2, d3) == None:cal_lis.append(None) else: cal_lis.append(div(d1-d2, d3)) if op[0] == "-" and op[1] == "+":cal_lis.append(d1-d2+d3) if op[0] == "-" and op[1] == "-":cal_lis.append(d1-d2-d3) # print(cal_lis) cal_lis = [int(cal) for cal in cal_lis if cal!=None] for res in cal_lis: if (res > 0 and res not in res_lis): res_lis.append(int(res)) for a in sorted(res_lis): print(a, end=" ") print()
考虑到除法条件也成立,是否有一种有效的方法来执行此任务(可能使用树?)
任何帮助将不胜感激...
假设我有三个整数。我想获得所有可能值的列表,这些值是通过在它们之间执行所有16个(*,/,+,-的4x4)操作获得的。就像我有3 4 1,我们应该得到...
您可以使用
itertools.combinations_with_replacement(ops_lis, len(mums) - 1)