This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

infix

By: phillip1882 on Jul 23rd, 2012  |  syntax: Python  |  size: 1.91 KB  |  views: 70  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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"))
clone this paste RAW Paste Data