The eval () function that calculates a string as an expression in python

Very convenient! I thought, so a memo The eval () function returns the calculation result with the character string of ** expression ** as an argument.

How to use

>>> 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

The eval () function that calculates a string as an expression in python
Get the formula in an excel file as a string in Python
A function that measures the processing time of a method in python
Get the caller of a function in Python
[Python] A function that searches the entire string with a regular expression and retrieves all matching strings.
Insert an object inside a string in Python
[Python] I tried to get the type name as a string from the type function
Check if the string is a number in python
# Function that returns the character code of a string
A function that easily calculates a listwise removal tree (Python)
What does the last () in a function mean in Python?
Create a function in Python
Note: The meaning of specifying only * (asterisk) as an argument in the Python function definition.
[Python] Leave only the elements that start with a specific character string in the array
A note that runs an external program in Python and parses the resulting line
Find out the apparent width of a string in python
Lambda expression (correction) that creates an index (dictionary with members as keys) of the members of the object being collected in python
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
Check the argument type annotation when executing a function in Python and make an error
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
[Python] Make the function a lambda function
Create a random string in Python
Create an instance of a predefined class from a string in Python
Play a sound in Python assuming that the keyboard is a piano keyboard
How to make a string into an array or an array into a string in Python
[Introduction to Python] How to split a character string with the split function
Format when passing a long string as an argument of python
python: Use the variables defined in the string format as they are
What's in the parameter? Edit String & Expression
Use print in a Python2 lambda expression
Precautions when pickling a function in python
Write the test in a python docstring
OR the List in Python (zip function)
Generate a class from a string in Python
[Python] A program that rounds the score
[Python] A program that calculates the number of chocolate segments that meet the conditions
If you want a singleton in python, think of the module as a singleton
[Python] A program that calculates the number of socks to be paired
I want to color a part of an Excel string in Python
[Introduction to Python] How to write a character string with the format function
[Python] Note: A self-made function that finds the area of the normal distribution
An error that does not work as expected when calling the tkinter module in a text editor
How to input a character string in Python and output it as it is or in the opposite direction.
Draw a graph of a quadratic function in Python
[Python] Get the files in a folder with Python
[Python] I want to know the variables in the function when an error occurs!
A solution to the problem that the Python version in Conda cannot be changed
A memo that I wrote a quicksort in Python
To execute a Python enumerate function in JavaScript
How to embed a variable in a python string
A program that removes duplicate statements in Python
Make a copy of the list in Python
Publish a Python module that calculates meteorological factors
Install the python package in an offline environment
Set an upper limit on the number of recursive function iterations in Python
I made a familiar function that can be used in statistics with Python
[Python] A program that calculates the difference between the total numbers on the diagonal line.
[Python] A program that calculates the number of updates of the highest and lowest records
Create a datetime object from a string in Python (Python 3.3)
[Python] A function that aligns the width by inserting a space in text that has both full-width and half-width characters.
Output in the form of a python array