1

I have a list in python like [1, '+', 32, '+', 56, '+', 34]. I am trying to do the math operation and get the final result as 123.

I have taken the input from user and had done the int conversion for numeric value and created this list now i want to give the final result.

I need some idea on how can i proceed with this.

Any help would be appreciable

anand2308
  • 35
  • 1
  • 7
  • 2
    Please show the code you're having trouble with - have a look at how to create a [mcve] – Jon Clements Aug 28 '17 at 13:16
  • 3
    Would you expect [1, '+', 2, '*', 3] to evaluate to 7 or 9? – holdenweb Aug 28 '17 at 13:18
  • Possible duplicate of [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – Chris_Rands Aug 28 '17 at 13:20
  • This is the exact code, where I am asking user to provide input and then I am creating 2 separate list one for numerics and another for operator, and then combining both to create a final list ________________________________________________ import re user_input = input("Please enter your input: \n") list1=(re.findall(r"[^\W\d_]+|\d+",user_input)) list2=(re.findall(r"[^0-9]",user_input)) list3=[] for a in range(0,len(list1)): if a < len(list2): list3.append(int(list1[a])) list3.append(list2[a]) else: list3.append(int(list1[a])) print (list3) – anand2308 Aug 28 '17 at 13:44
  • @JonClements The question is now clear, but might I suggest marking as a dupe, I worry that the accepted answer is promoting the use of the insecure `eval()` – Chris_Rands Aug 28 '17 at 14:59
  • If you want an answer without eval, check out my list comprehension solution – whackamadoodle3000 Aug 28 '17 at 23:51

3 Answers3

4

Quick way:

eval(' '.join(str(x) for x in  [1, '+', 32, '+', 56, '+', 34]))
user2021091
  • 561
  • 2
  • 11
  • Just about the only time I think `eval` is actually the very best tool for the job – bendl Aug 28 '17 at 13:24
  • 3
    @bendl Disagree! This is a security risk, the OP says "I have taken the input from user and had done the int conversion for numeric value and created this list ", presumably if there are not `int`s this will be parsed unsafely, e.g. `eval(' '.join(str(x) for x in ["__import__('os').system('ls')"]))` – Chris_Rands Aug 28 '17 at 13:27
  • @Chris_Rands I missed that part of the question, true. But if it's a real security concern it should be quite easy to restrict input to only `+` `-` `*` `/` – bendl Aug 28 '17 at 13:28
  • 1
    @bendl Of course they need to built a parser (and those are not the only operators), that's why I suggested this dupe https://stackoverflow.com/a/9558001/6260170 – Chris_Rands Aug 28 '17 at 13:32
  • @Chris_Rands that's another good solution, but I think eval is really very pythonic. Sometimes security just isn't a concern. I agree that it should stay WAY out of reach of the public, but saying that no one can use a keyword under any circumstance like many do is a little silly. Understand the risk, definitely, but don't let a non-existent security threat make your code ugly – bendl Aug 28 '17 at 13:37
  • @bendl I will put a check so that user can only input required data, can you please explain what is happening in the eval command. It will be of great help – anand2308 Aug 28 '17 at 13:47
  • @anand2308 [See the docs](https://docs.python.org/3/library/functions.html#eval) @user2021091 is taking your list and joining it with a space, creating a string: `"1 + 32 + 56 + 34"`. `eval` then *evaluates* the string as if it were copy and pasted into a python interpreter and returns the output. – bendl Aug 28 '17 at 13:50
  • Thank you so much, that explain all :) – anand2308 Aug 28 '17 at 13:53
0

I find eval to be a kind of ugly solution; I would recommend approaching it this way:

from operator import add, sub

def process(instructions):
    result = 0
    operations = {'+': add, '-': sub}
    operation = add 
    for item in instructions:
        if item in operations:
            operation = operations[item]
        else:
            number = float(item)
            result = operation(result, number)
    return result

your_instructions = [1, '+', 32, '+', 56, '+', 34]
process(your_instructions)
Ben Quigley
  • 727
  • 4
  • 18
0
a=[1, '+', 32, '+', 56, '+', 34]
sum([elem for elem in a if elem!='+'])

How about taking out the plus signs and using sum

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44