curriculum/challenges/english/blocks/daily-coding-challenges-python/69b559d2903b9e4afe9075f7.md
Given a string representing a math equation, determine whether it is correct.
+, -, *, and /."number operator number = number" (with two or three numbers on the left). For example: "2 + 2 = 4" or "2 + 3 - 1 = 4".Follow standard order of operations: multiplication and division are evaluated before addition and subtraction, from left-to-right.
is_valid_equation("2 + 2 = 4") should return True.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("2 + 2 = 4"), True)`)
}})
is_valid_equation("2 + 3 - 1 = 4") should return True.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("2 + 3 - 1 = 4"), True)`)
}})
is_valid_equation("8 / 2 = 4") should return True.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("8 / 2 = 4"), True)`)
}})
is_valid_equation("10 * 5 = 50") should return True.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("10 * 5 = 50"), True)`)
}})
is_valid_equation("2 - 2 = 0") should return True.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("2 - 2 = 0"), True)`)
}})
is_valid_equation("2 + 9 / 3 = 5") should return True.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("2 + 9 / 3 = 5"), True)`)
}})
is_valid_equation("20 - 2 * 3 = 14") should return True.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("20 - 2 * 3 = 14"), True)`)
}})
is_valid_equation("2 + 5 = 6") should return False.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("2 + 5 = 6"), False)`)
}})
is_valid_equation("10 - 2 * 3 = 24") should return False.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("10 - 2 * 3 = 24"), False)`)
}})
is_valid_equation("3 + 9 / 3 = 4") should return False.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_equation("3 + 9 / 3 = 4"), False)`)
}})
def is_valid_equation(equation):
return equation
def is_valid_equation(equation):
left, right = equation.split(" = ")
tokens = left.split(" ")
i = 1
while i < len(tokens) - 1:
op = tokens[i]
if op in ("*", "/"):
a = int(tokens[i - 1])
b = int(tokens[i + 1])
computed = a * b if op == "*" else a // b
tokens[i - 1:i + 2] = [str(computed)]
else:
i += 2
result = int(tokens[0])
i = 1
while i < len(tokens) - 1:
op = tokens[i]
val = int(tokens[i + 1])
result = result + val if op == "+" else result - val
i += 2
return result == int(right)