There is an interesting task for computing values inside of list.
[2025, 'minus', 5, 'plus', 3]
2023
[2, 'multiply', 13]
26
Any suggestions how it can be implemented in python3?
There is an interesting task for computing values inside of list.
[2025, 'minus', 5, 'plus', 3]
2023
[2, 'multiply', 13]
26
Any suggestions how it can be implemented in python3?
As suggested by @roganjosh create a dict and perform the operations
import operator
ops = { "plus": operator.add, "minus": operator.sub,'multiply':operator.mul, 'divide':operator.div }
a=[2025, 'minus', 5, 'plus',3]
try:
val=int(a[0])
stack=[]
error=False
for i in range(1,len(a)):
if isinstance(a[i],str):
stack.append(a[i])
if isinstance(a[i],int):
temp_operator =stack.pop()
operation=ops.get(temp_operator)
val=operation(val,a[i])
except Exception:
print('Invalid input')
error=True
if(stack):
print('Invalid input')
error=True
if(not error):
print(val)
Output
2023
Solution
import operator
string_operator = {
"plus" : operator.add,
"minus" : operator.sub,
"multiply" : operator.mul,
"divide" : operator.truediv}
problem = [2025, "minus", 5, "plus", 3]
for i in range(len(problem)):
if problem[i] in string_operator.keys():
problem[i] = string_operator[problem[i]]
solution = problem[i](problem[i-1],problem[i +1])
problem[i+1] = solution
print(solution)
Output
(xenial)vash@localhost:~/python$ python3 helping.py 2023
for problem = [2, "multiply", 13]
:
(xenial)vash@localhost:~/python$ python3 helping.py 26
Comments
This will follow the code along and process the operators in the order they are presented, wasn't sure if you wanted to follow order of operations, there was no mention of it.
First I created a dictionary to convert the strings to actual operators (note division has to be either truediv
or floordiv
).
Then using a for loop if the item in problem
is one of the operators. The string will then be converted into the appropriate operator (problem[i] = string_operator[problem[i]]
it will take the values before (i-1
) and (i+1
) the operator and compute them
(solution = problem[i](problem[i-1], problem[i+1])
.
To keep the computation going I then store that output in the item following said operator (i+1
), which by your setup will be the item prior to the next operator, which will allow the process to continue.
For fun
problem = [26, "multiply", 100, "divide", 2, "plus", 40, "minus", 3]
(xenial)vash@localhost:~/python$ python3 helping.py 1337
:)