Python | Solve given list containing numbers and arithmetic operators
Last Updated :
11 Apr, 2023
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.
Python3
# 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)
Output:Initial list [91, '+', 132, '-', 156, '+', 4]
Answer after solving list is: 71.0
Method #2: Using eval and join
Python3
# 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)
Output:Initial list [2, '+', 22, '+', 55, '+', 4]
Answer after solving list is: 83
Approach#3: Using loop
This approach defines a function that takes a list containing numbers and arithmetic operators and evaluates the expression. It initializes the result to the first number in the list and iterates through the remaining items in pairs. Depending on the operator in the current pair, it performs addition, subtraction, multiplication, or division on the result and the next number in the list. The final result is returned.
Algorithm
1. Initialize a variable result to the first element of the list.
2. Traverse the list from index 1 to n-1.
3. If the current element is an operator, apply it on the result and the next element.
4. If the current element is a number, ignore it.
5. Return the final result.
Python3
def evaluate_expression(lst):
result = lst[0]
for i in range(1, len(lst)-1, 2):
if lst[i] == '+':
result += lst[i+1]
elif lst[i] == '-':
result -= lst[i+1]
elif lst[i] == '*':
result *= lst[i+1]
elif lst[i] == '/':
result /= lst[i+1]
return result
lst = [2, '+', 22, '+', 55, '+', 4]
print(evaluate_expression(lst)) # 83
lst = [12, '+', 8, '-', 5]
print(evaluate_expression(lst)) # 15
Time Complexity: O(n), where n is the length of the list.
Space Complexity: O(1)
Similar Reads
Check if a Number is a Whole Number in Python Checking if a Number is a Whole Number in Python means determining whether the number has no fractional part, using custom logic instead of relying on assumptions about its type. For example, a number like 7.0 is considered whole, while 7.5 is not. Letâs explore various methods to do it accurately.U
2 min read
Sum of number digits in List in Python Our goal is to calculate the sum of digits for each number in a list in Python. This can be done by iterating through each number, converting it to a string, and summing its digits individually. We can achieve this using Pythonâs built-in functions like sum(), map(), and list comprehensions. For exa
2 min read
Python - Operation to each element in list Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
2 min read
Python program to compute arithmetic operation from String Given a String with the multiplication of elements, convert to the summation of these multiplications. Input : test_str = '5x10, 9x10, 7x8' Output : 196 Explanation : 50 + 90 + 56 = 196. Input : test_str = '5x10, 9x10' Output : 140 Explanation : 50 + 90 = 140. Method 1 : Using map() + mul + sum() +
4 min read
Python Program to Convert a list of multiple integers into a single integer There are times when we need to combine multiple integers from a list into a single integer in Python. This operation is useful where concatenating numeric values is required. In this article, we will explore efficient ways to achieve this in Python.Using join()join() method is the most efficient an
2 min read
Python Program to calculate sum and average of three numbers We are given three numbers, and our task is to calculate the sum and average of these numbers. The average of the numbers is defined as the sum of the given numbers divided by the total number of elements. In this case, it will be the sum of given three numbers divided by 3. Example: Input: 10, 20,
3 min read