Bora vê
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

infixtoposfix.py 1.1KB

12345678910111213141516171819202122232425262728293031323334353637
  1. '''
  2. Codigo retirado do livro: Problem Solving with Algorithms and Data Structures using Python
  3. pelo link: http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
  4. e modificado por: Nicolas T. Cuerbas
  5. '''
  6. def infixToPostfix(infixexpr):
  7. prec = {}
  8. prec["*"] = 3
  9. prec["/"] = 3
  10. prec["+"] = 2
  11. prec["-"] = 2
  12. prec[">"] = 2
  13. prec["<"] = 2
  14. prec["("] = 1
  15. opStack = []
  16. postfixList = []
  17. tokenList = infixexpr.split()
  18. for token in tokenList:
  19. if token.isidentifier() or token.isdigit():
  20. postfixList.append(token)
  21. elif token == '(':
  22. opStack.extend(token)
  23. elif token == ')':
  24. topToken = opStack.pop()
  25. while topToken != '(':
  26. postfixList.append(topToken)
  27. topToken = opStack.pop()
  28. else:
  29. while (not len(opStack)==0) and (prec[opStack[-1]] >= prec[token]):
  30. postfixList.append(opStack.pop())
  31. opStack.extend(token)
  32. while not (len(opStack)==0):
  33. postfixList.append(opStack.pop())
  34. return " ".join(postfixList)