0

I am trying to use a list that has operations attached to them, but i can't get the numbers out of the list. Here is the list.

mylist=["+1", "-2", "*2"]

I was wondering if there was a way to put them together as a float, and then do the operation so it would do 1-2*2 and output the answer. Smaller the better. thanks :) the expected output is -2.

15
  • 5
    These are strings? Commented Jan 15, 2018 at 0:45
  • 2
    mylist=[+1, -2, *2] is illegal in Python. Commented Jan 15, 2018 at 0:48
  • 1
    What is the expcted result for the given list: -2 or -3 Commented Jan 15, 2018 at 1:13
  • 1
    @schwobaseggl -2 Commented Jan 15, 2018 at 1:15
  • 1
    @Alpha You should put that in your post as it clears up the precedence of operations Commented Jan 15, 2018 at 1:15

2 Answers 2

2

You can use a dict to map symbols to operations (that are all defined in operator) and regular expressions to parse the strings in order to avoid evil eval. This applies the operations in the list from left to right, regardless of mathematical operator precedence:

import re
from operator import add, sub, mul, truediv  # use 'floordiv' for integer division

def calc(lst):
    ops = {'+': add, '-': sub, '*': mul, '/': truediv}
    result = 0
    for x in lst:
        op, num = re.match(r'([+\-\*/])(\d+)', x).groups()
        result = ops[op](result, int(num))
    return result

>>> calc(['+1', '-2', '*2'])
-2
>>> calc(['+1', '-2', '*2', '+7', '*3'])
15
Sign up to request clarification or add additional context in comments.

3 Comments

Does +1-2*2 really evaluate to -2?
@DYZ ...which the OP expects, as it turned out :)
I guess you win, then :)
0

By treating your example as a string, it is possible to compute the output after each operation listed, assuming the input is treated with precedence from left to right:

from collections import namedtuple
import re
token = namedtuple('token', 'operator, value')
mylist="[+1, -2, *2]"
data = re.findall('[\+\-\*]|\d+', mylist)
final_data = [data[i:i+2] for i in range(0, len(data), 2)] #create tokenized list
tokens = [token(a, int(b)) for a, b in final_data] 
operations = {'+':lambda x,y:x+y, '-':lambda x, y:x-y, '*':lambda x, y:x*y}
total_val = 0
for token in tokens:
   total_val = operations[token.operator](total_val, token.value)

Output:

-2

2 Comments

Why does 1-2*2 evaluate to -2?
@DYZ unless the OP clarifies with regard to the proper order, this answer treats the data with precedence from left to right, as I believe adding ( and ) is out of scope of this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.