Very convenient! I thought, so a memo The eval () function returns the calculation result with the character string of ** expression ** as an argument.
>>> eval("1 + 2")
3
>>> eval("1" "2")
12
>>> eval("1" + "2")
12
>>> eval("1" "+" "2")
3
When to use it, I used it in [This problem] of AtCoder (https://atcoder.jp/contests/arc061/tasks/arc061_a).
Problem statement You will be given the string S, which consists only of numbers between 1 and 9. Within this string, you can put a + in some places between these characters. You don't have to put in one. However, the + must not be consecutive. All the strings created in this way can be regarded as mathematical expressions and the sum can be calculated. Calculate the values of all possible formulas and output the sum.
from itertools import product
s = list(input())
n = len(s)
answer = 0
pattern = list(product(['+', ''], repeat=n-1))
for i in range(2 ** (n-1)):
formula = s[0]
for j, k in zip(pattern[i], s[1:]):
formula += (j + k)
answer += eval(formula)
print(answer)
Recommended Posts