Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the missing value from the given equation a + b = c in Python
In Python, we can solve equations of the form a + b = c where one value is missing (represented by ?). This involves parsing the equation string and applying basic arithmetic to find the unknown value.
For example, if the input is ? + 4 = 9, the output will be 5.
Algorithm
To solve this problem, we follow these steps:
Remove all spaces from the string and replace
+and=with commasSplit the string by commas to get individual elements
Find the position of the missing value (
?)-
Apply the appropriate arithmetic operation based on position:
If
cis missing: returna + bIf
bis missing: returnc - aIf
ais missing: returnc - b
Implementation
def find_missing(equation):
# Remove spaces and replace operators with commas
equation = equation.strip().replace(' ', '')
equation = equation.replace('=', ',')
equation = equation.replace('+', ',')
# Split into elements
elements = equation.split(',')
# Find position of missing value
missing_idx = 0
for i in range(len(elements)):
if not elements[i].isnumeric():
missing_idx = i
break
# Calculate missing value based on position
if missing_idx == 2: # c is missing (a + b = ?)
return int(elements[0]) + int(elements[1])
elif missing_idx == 1: # b is missing (a + ? = c)
return int(elements[2]) - int(elements[0])
elif missing_idx == 0: # a is missing (? + b = c)
return int(elements[2]) - int(elements[1])
# Test cases
print(find_missing('6 + 8 = ?'))
print(find_missing('? + 8 = 20'))
print(find_missing('5 + ? = 15'))
14 12 10
How It Works
The solution works by transforming the equation string into a list of elements:
'6 + 8 = ?'becomes['6', '8', '?']We identify which position contains the
?Based on the position, we apply the correct arithmetic operation
Alternative Approach Using eval()
def find_missing_eval(equation):
# Split by '=' to get left and right parts
left, right = equation.split('=')
left, right = left.strip(), right.strip()
if '?' in left:
# Unknown is on the left side
if '+' in left:
parts = left.split('+')
if '?' in parts[0].strip():
return int(right) - int(parts[1].strip())
else:
return int(right) - int(parts[0].strip())
else:
# Unknown is on the right side (c = ?)
parts = left.split('+')
return int(parts[0].strip()) + int(parts[1].strip())
# Test cases
print(find_missing_eval('6 + 8 = ?'))
print(find_missing_eval('? + 8 = 20'))
print(find_missing_eval('5 + ? = 15'))
14 12 10
Conclusion
Both approaches effectively solve missing value problems in simple addition equations. The first method uses string parsing and position-based logic, while the second approach splits by the equals sign for cleaner handling of equation sides.
