phillip1882

infix

Jul 23rd, 2012
112
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import re
  2.  
  3. def factor(elements):
  4.    i = 0
  5.    value = 1
  6.    token = "*"
  7.    while "/" in elements or "*" in elements:
  8.       if elements[i+1] == "*":
  9.          if token == "*":
  10.             value *= int(elements[i])
  11.          else:
  12.             value /= int(elements[i])
  13.          token = "*"
  14.          elements.pop(i+1)
  15.       elif elements[i+1] == "/":
  16.          if token == "*":
  17.             value *= int(elements[i])
  18.          else:
  19.             value /= int(elements[i])
  20.          token = "/"
  21.          elements.pop(i+1)
  22.       i +=  1
  23.    if token == "*":
  24.       value *= int(elements[i])
  25.    else:
  26.       value /= int(elements[i])
  27.    return int(value)
  28.  
  29. def expr(elements):
  30.    i = 0
  31.    value = 0
  32.    token = "+"
  33.    while  "-" in elements or "+" in elements:
  34.       if elements[i+1] == "+":
  35.          if token == "+":
  36.             value += factor(elements[:i+1])
  37.          else:
  38.             value -= factor(elements[:i+1])
  39.          token = "+"
  40.          elements = elements[i+2:]
  41.          i = 0
  42.       elif elements[i+1] == "-":
  43.          if token == "+":
  44.             value += factor(elements[:i+1])
  45.          else:
  46.             value -= factor(elements[:i+1])
  47.          token = "-"
  48.          elements = elements[i+2:]
  49.          i = 0
  50.       i +=  1
  51.    if token == "+":
  52.       value += factor(elements)
  53.    else:
  54.       value -= factor(elements)
  55.    return value
  56.  
  57.    
  58. def infix(string1):
  59.    tokens = re.split('(\W)',string1)
  60.    i = 0
  61.    while '' in tokens or ' ' in tokens[i] :
  62.       if tokens[i] == ' ' or tokens[i] =='':
  63.          tokens.pop(i)
  64.       i+= 1
  65.    i = 0
  66.    j = 0
  67.    while ')' in tokens:
  68.       if tokens[i] != ")":
  69.          i += 1
  70.          j = i
  71.          while tokens[j] != "(":
  72.             j -= 1
  73.       if tokens[i] == ")" and tokens[j] == "(":
  74.          tokens = tokens[:j]+[str(expr(tokens[j+1:i]))]+tokens[i+1:]
  75.          i = 0
  76.    value = expr(tokens)
  77.    return value
  78. print(infix("27*((15+36)/2)-7"))
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×