Your task is to define a function that understands basic mathematical expressions and solves them.
For example:

```python
calculate("1 + 1")        # => 2
calculate("18 + 4*6")     # => 42
calculate("245 - 826")    # => -581
calculate("09 + 000482")  # => 491
calculate("8 / 4 + 6")    # => 8
calculate("5 + 1 / 5")    # => 5.2
calculate("1+2+3")        # => 6
calculate("9 /3 + 12/ 6") # => 5
```
Notes:

- Input string will contain numbers (may be integers and floats) and arithmetic operations.
- Input string may contain spaces, and all space characters should be ignored.
- Operations that will be used: addition (+), subtraction (-), multiplication (*), and division (/)
- Operations must be done in the order of operations: First multiplication and division, then addition and subtraction.
- In this kata, input expression will not have negative numbers. (ex: "-4 + 5")
- If output is an integer, return as integer. Else return as float.
- If input string is empty, contains letters, has a wrong syntax, contains division by zero or is not a string, return False.

Difficulty: EASY
Tags: String algorithms

Mathematics

Starter code:
def calculate(input):
	

Solutions:
import re

def calculate(input):
	try:
		return eval(re.sub('(\\d+)', lambda m: str(int(m.group(1))), input))
	except:
		return False


import re

def calculate(s):
	try:
		s = re.sub('(?<!\\d)0+(0|[1-9]\\d*)', lambda m: m.group(1), s)
		s = re.sub('\\d+(?!\\.)', lambda m: m.group() + '.0', s)
		return eval(s)
	except:
		return False


import math

def solve(s: list, mp=0):
	LHS = s.pop(0)
	while len(s) > 0:
		op = s[0]
		p = 1 if op in '+-' else 2
		if p < mp:
			break
		p += 1
		s.pop(0)
		RHS = solve(s, p)
		if op == '+':
			LHS += RHS
		elif op == '-':
			LHS -= RHS
		elif op == '*':
			LHS *= RHS
		elif RHS != 0:
			LHS /= RHS
		else:
			return math.nan
	return LHS

def calculate(s):
	try:
		s = s.replace(' ', '')
	except:
		return False
	dim = len(s)
	if dim == 0:
		return False
	for c in s:
		if not c in '0123456789.+-*/':
			return False
	for i in range(dim - 1):
		if s[i] in '+-*/' and s[i + 1] in '+-*/':
			return False
	exp = []
	i = 0
	for (j, c) in enumerate(s):
		if i == j:
			pass
		elif c in ['+', '-', '*', '/']:
			try:
				exp.append(float(s[i:j]))
			except:
				return False
			exp.append(s[j])
			i = j + 1
	try:
		exp.append(float(s[i:]))
	except:
		return False
	v = solve(exp)
	if math.isnan(v):
		return False
	if float(v) == float(int(v)):
		return int(v)
	return v


from re import sub

def calculate(input):
	try:
		return eval(sub('([^\\d])0+(\\d)', '\\1\\2', input))
	except:
		return False


import re

def calculate(s):
	try:
		return eval(re.sub('\\b0+(?=[1-9])', '', s))
	except:
		return False


import re

def calculate(input):
	try:
		for n in re.findall('\\d+', input):
			input = input.replace(n, n.lstrip('0') or '0')
		return eval(input)
	except:
		return False


import functools as ft
import math
ops = ['*', '/', '+', '-']

def SanitizeExpression(expression):
	return expression.replace('+-', '-').replace('-+', '-').replace('--', '+')
	pass

def ExtendList(arr, value, op):
	arr.extend(value.split(op))
	return arr

def LastIndexOfAny(expression, operators, startIndex):
	arr = [expression[0:startIndex].rfind(x) for x in operators]
	arr.sort()
	return arr[-1]
	pass

def IndexOfAny(expression, operators, startIndex):
	arr = [x + startIndex for x in [expression[startIndex:].find(x) for x in operators] if x != -1]
	if len(arr) == 0:
		arr = [-1]
	arr.sort()
	return arr[0]
	pass

def FloatToString(value):
	return '%.30f' % value
	pass

def EvaluateSimpleExpression(expression):
	numberText = expression.split(ops[0])
	numberText = ft.reduce(lambda r, s: ExtendList(r, s, ops[2]), numberText, [])
	numberText = ft.reduce(lambda r, s: ExtendList(r, s, ops[3]), numberText, [])
	numberText = ft.reduce(lambda r, s: ExtendList(r, s, ops[1]), numberText, [])
	numbers = [float(x) for x in numberText if x != '']
	minusCount = expression.count('-')
	if expression.count('*') > 0:
		return numbers[0] * numbers[1] * math.pow(-1, minusCount)
	if expression.count('/') > 0:
		return numbers[0] / numbers[1] * math.pow(-1, minusCount)
	if expression.count('-') > 0:
		return numbers[0] - numbers[1]
	return numbers[0] + numbers[1]
	pass

def ResolveSimpleExpression(expression, operatorIndex):
	startIndex = LastIndexOfAny(expression, ops, operatorIndex - 1) + 1
	indexNext = IndexOfAny(expression, ops, operatorIndex + 2)
	if indexNext == -1:
		length = len(expression)
	else:
		length = indexNext
	length -= startIndex
	return expression[startIndex:startIndex + length]
	pass

def EvaluateSimpleInComplexExpression(expression, operatorIndex):
	simple = ResolveSimpleExpression(expression, operatorIndex)
	simpleAns = EvaluateSimpleExpression(simple)
	if math.fabs(simpleAns) < 1e-10:
		simpleAns = 0
		pass
	insertIndex = expression.find(simple)
	return expression[0:insertIndex] + FloatToString(simpleAns) + expression[insertIndex + len(simple):]
	pass

def SimplifyExpressionByOperatorsRec(expression, applyNegative, multiplier, operators):
	if expression[0] == '+':
		expression = expression[1:]
	if applyNegative and expression[0] == '-':
		multiplier *= -1
		expression = expression[1:].replace('+', 'X').replace('-', '+').replace('X', '-')
		pass
	indexArr = [x for x in [expression.find(op) for op in operators] if x > 0]
	if len(indexArr) > 0:
		indexArr.sort()
		index = indexArr[0]
		expression = EvaluateSimpleInComplexExpression(expression, index)
		expression = SanitizeExpression(expression)
		return SimplifyExpressionByOperatorsRec(expression, applyNegative, multiplier, operators)
		pass
	try:
		return FloatToString(float(expression) * multiplier)
	except:
		return expression
	pass

def SimplifyExpressionByOperators(expression, applyNegative, operators):
	return SimplifyExpressionByOperatorsRec(expression, applyNegative, 1, operators)

def EvaluateComplexExpression(expression):
	result = SimplifyExpressionByOperators(expression, False, ['*', '/'])
	return SimplifyExpressionByOperators(result, True, ['+', '-'])
	pass

def EvaluateBracketExpression(expression):
	closeIndex = expression.find(')')
	if closeIndex >= 0:
		openIndex = expression[0:closeIndex].rfind('(')
		startIndex = openIndex + 1
		length = closeIndex - startIndex
		complexExp = expression[startIndex:closeIndex]
		resolved = EvaluateComplexExpression(complexExp)
		expression = expression[0:openIndex] + str(resolved) + expression[openIndex + length + 2:]
		expression = SanitizeExpression(expression)
		return EvaluateBracketExpression(expression)
		pass
	return EvaluateComplexExpression(expression)
	pass

def calculate(expression):
	try:
		test = 'string' + expression
	except:
		return False
	expression = str(expression).replace(' ', '')
	if expression == '':
		return 0
	expression = SanitizeExpression(expression)
	try:
		return float(EvaluateBracketExpression(expression))
	except:
		return False
	pass


from re import sub

def calculate(s):
	try:
		return eval(sub('\\b0+(?=\\d)', '', s))
	except:
		return 0


class Calculator(object):
	operators = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y}
	high_pre = ['*', '/']

	def __init__(self):
		self.operand = []
		self.operator = []

	def parse_string(self, string):
		index = 0
		while index < len(string):
			end = index + 1
			while end < len(string) and string[end] not in list(self.operators.keys()):
				end += 1
			try:
				self.operand.append(float(string[index:end]))
			except:
				return False
			if end < len(string):
				self.operator.append(string[end])
			index = end + 1
		return True

	def evaluate(self, string=''):
		if string == '':
			string = '0'
		valid = self.parse_string(string)
		if not valid:
			return False
		while len(self.operand) != 1:
			operator_index = len(string)
			for op in self.high_pre:
				if op in self.operator:
					operator_index = min(operator_index, self.operator.index(op))
			if operator_index == len(string):
				operator_index = 0
			x = self.operand[operator_index]
			y = self.operand[operator_index + 1]
			op = self.operator[operator_index]
			try:
				self.operand[operator_index] = self.operators[op](x, y)
			except:
				return False
			self.operand.pop(operator_index + 1)
			self.operator.pop(operator_index)
		return self.operand[0]

def calculate(input):
	if type(input) != str:
		return False
	return Calculator().evaluate(input)


digits = '0123456789'
ops = '+-/*'

def calc(expr):
	r = []
	i = 0
	t = len(expr)
	c = ''
	s = ''
	left = 0
	right = 0
	cur_idx = 0
	while i < t:
		c = expr[i]
		if c in digits:
			if not s:
				s = c
			elif s[-1] in digits:
				s += c
			else:
				r += [s]
				s = c
		elif c == ' ':
			pass
		elif c in ops:
			r += [s] if s != '' else []
			r += [c]
			s = ''
		elif c == '(':
			left = 1
			right = 0
			cur_idx = i
			while i < t and left != right:
				i += 1
				if expr[i] == '(':
					left += 1
				elif expr[i] == ')':
					right += 1
			r += [calc(expr[cur_idx + 1:i])]
		i += 1
	r += [s] if s != '' else []
	r_new = []
	for item in r:
		try:
			r_new.append(float(item))
		except ValueError:
			r_new.append(item)
	r = list(r_new)
	r_new = []
	i = 0
	t = len(r)
	while i < t:
		if r[i] == '-':
			if type(r[i + 1]) == float:
				r_new.append(-r[i + 1])
			elif r[i + 1] == '-':
				sign = 1
				while r[i + 1] == '-':
					sign *= -1
					i += 1
				r_new.append(sign * r[i])
				i -= 1
			else:
				r_new.append(r[i])
				r_new.append(r[i + 1])
			i += 2
		else:
			r_new.append(r[i])
			i += 1
	r_new = [d for d in r_new if d != '']
	while '*' in r_new or '/' in r_new:
		t = len(r_new)
		mul_idx = r_new.index('*') if '*' in r_new else t
		div_idx = r_new.index('/') if '/' in r_new else t
		if mul_idx == 0 or div_idx == 0:
			raise Exception()
		cur_idx = min(mul_idx, div_idx)
		new_numb = r_new[cur_idx - 1] * r_new[cur_idx + 1] if cur_idx == mul_idx else r_new[cur_idx - 1] / r_new[cur_idx + 1]
		r_new = r_new[:cur_idx - 1] + [new_numb] + r_new[cur_idx + 2:]
	return sum([d for d in r_new if d != '+'])

def calculate(x):
	if x == '':
		return False
	try:
		return calc(x)
	except:
		return False