Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- def factor(elements):
- i = 0
- value = 1
- token = "*"
- while "/" in elements or "*" in elements:
- if elements[i+1] == "*":
- if token == "*":
- value *= int(elements[i])
- else:
- value /= int(elements[i])
- token = "*"
- elements.pop(i+1)
- elif elements[i+1] == "/":
- if token == "*":
- value *= int(elements[i])
- else:
- value /= int(elements[i])
- token = "/"
- elements.pop(i+1)
- i += 1
- if token == "*":
- value *= int(elements[i])
- else:
- value /= int(elements[i])
- return int(value)
- def expr(elements):
- i = 0
- value = 0
- token = "+"
- while "-" in elements or "+" in elements:
- if elements[i+1] == "+":
- if token == "+":
- value += factor(elements[:i+1])
- else:
- value -= factor(elements[:i+1])
- token = "+"
- elements = elements[i+2:]
- i = 0
- elif elements[i+1] == "-":
- if token == "+":
- value += factor(elements[:i+1])
- else:
- value -= factor(elements[:i+1])
- token = "-"
- elements = elements[i+2:]
- i = 0
- i += 1
- if token == "+":
- value += factor(elements)
- else:
- value -= factor(elements)
- return value
- def infix(string1):
- tokens = re.split('(\W)',string1)
- i = 0
- while '' in tokens or ' ' in tokens[i] :
- if tokens[i] == ' ' or tokens[i] =='':
- tokens.pop(i)
- i+= 1
- i = 0
- j = 0
- while ')' in tokens:
- if tokens[i] != ")":
- i += 1
- j = i
- while tokens[j] != "(":
- j -= 1
- if tokens[i] == ")" and tokens[j] == "(":
- tokens = tokens[:j]+[str(expr(tokens[j+1:i]))]+tokens[i+1:]
- i = 0
- value = expr(tokens)
- return value
- print(infix("27*((15+36)/2)-7"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement