问题
I want to check if 7 digits can get to 100 when putting elementary arithmetic symbols between them.
def is_hundred(n1,n2,n3,n4,n5,n6,n7):
p = [+,-,*,/]
for p1 in p:
for p2 in p:
for p3 in p:
for p4 in p:
for p5 in p:
for p6 in p:
if n1 p1 n2 p2 n3 p3 n4 p4 n5 p5 n6 p6 n7 == 100:
return "success"
how can i replace the variables with the arithmetic symbols that are in the list?
回答1:
In case you didn't hear it: using eval is evil. So that's definitely not code that I'd put in production. That said, this exercise is also something that I will probably never have to deploy to prod...
The idea: use the arguments and "brute-force" all the possibilities of adding operations between them. Construct these options as strings, and for each one of them, when done, evaluate the total (using eval
) and if the total is 100 - print it to stdout:
def is_hundred(args, res=''):
if res == '':
res = args[0]
args = args[1:]
if not args:
if eval(res) == 100:
print(res)
else:
first = args[0]
for op in ['+','-','*','/']:
is_hundred(args[1:], "{}{}{}".format(res, op, first))
# you can pass any number of arguments in a list: 7, 8, 15...
is_hundred([2,3,4,8,10,11]) # 2+3+4+8*10+11
回答2:
Here is a sample code which search a pair of operators. the i
in iadd
means inplace add
operator. You can simply switch to add
. product
creates duplicate permutation of operators.
from operator import iadd, isub, imul, itruediv
from itertools import product
operators = (iadd, isub, imul, itruediv)
def is_hundred(values):
n_operators = len(values) - 1
for ops in product(operators, repeat=n_operators):
value = values[0]
for op, v in zip(ops, values[1:]):
value = op(value, v)
if value == 100:
print(list(ops))
return True
else:
return False
print(is_hundred([99,1,1,1,1,1]))
print(is_hundred([1,1,1,1]))
来源:https://stackoverflow.com/questions/47616114/how-to-loop-over-the-elementary-arithmetic-symbols