-3

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?

Ivan Shelonik
  • 1,958
  • 5
  • 25
  • 49
  • What would be output of `[2, 'multiply', 13, 14]` or `['minus']` – mad_ Aug 31 '18 at 15:18
  • The principle shouldn't really be any different than [this](https://stackoverflow.com/questions/1740726/turn-string-into-operator) – roganjosh Aug 31 '18 at 15:21
  • @mad_ is going to raise Error – Ivan Shelonik Aug 31 '18 at 15:26
  • @roganjosh I cannot hardcode it because I have to know exactly the position of each element to compute it via operator. I want it to be computed automatically for any type of given values. If it could easely converted via dictionary of operators like x1 operator.add x2 operator.sub there were questions at all – Ivan Shelonik Aug 31 '18 at 15:27
  • 1
    Above comment of @roganjosh is not about hardcoding the values it is about creating a dict object of operators – mad_ Aug 31 '18 at 15:30
  • @IvanShelonik but you can use `get()` on your operator dictionary to see whether each string is a recognised operator, else convert to a numerical value – roganjosh Aug 31 '18 at 15:36

2 Answers2

2

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
mad_
  • 8,121
  • 2
  • 25
  • 40
1

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

:)

vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20