Python | Solve given list containing numbers and arithmetic operators

Given a list containing numbers and arithmetic operators, the task is to solve the list.

Example:

Input: lst =  [2, '+', 22, '+', 55, '+', 4]
Output: 83

Input: lst =  [12, '+', 8, '-', 5]
Output: 15

Below are some ways to achieve the above tasks.



Method #1: Using Iteration
We can use iteration as the simplest approach to solve the list with importing different operators.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to solve the list
# containing numbers and arithmetic operators
  
# Importing
from operator import add, sub
  
# Function to solve list
def find(Input):
    ans = 0
    options = {'+': add, '-': sub}
    option = add 
    for item in Input:
        if item in options:
            option = options[item]
        else:
            number = float(item)
            ans = option(ans, number)
    return ans
  
# Input Initialization
lst = [91, '+', 132, '-', 156, '+', 4]
  
# Calling function
Output = find(lst)
  
# Printing output
print("Initial list", lst)
print("Answer after solving list is:", Output)

chevron_right


Output:

Initial list [91, '+', 132, '-', 156, '+', 4]
Answer after solving list is: 71.0

Method #2: Using eval and join

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to solve the list
# containing numbers and arithmetic operators
  
# Input list initialization
lst =  [2, '+', 22, '+', 55, '+', 4]
  
# Using eval and join
Output = eval(' '.join(str(x) for x in lst))
  
# Printing output
print("Initial list", lst)
print("Answer after solving list is:", Output)

chevron_right


Output:

Initial list [2, '+', 22, '+', 55, '+', 4]
Answer after solving list is: 83


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.