Няма описание

taschenrechner.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. symbol_priority = {}
  2. symbol_priority[0] = ['#']
  3. symbol_priority[1] = ['(']
  4. symbol_priority[2] = ['+', '-']
  5. symbol_priority[3] = ['*', '/']
  6. symbol_priority[4] = [')']
  7. def comparePriority(symbol, RPN_stack, symbol_stack):
  8. global symbol_priority
  9. if len(symbol_stack) > 0:
  10. symbol_pop = symbol_stack.pop()
  11. else:
  12. return
  13. for list in symbol_priority.values():
  14. if (symbol in list) and (symbol_pop in list):
  15. symbol_stack.append(symbol_pop)
  16. symbol_stack.append(symbol)
  17. return
  18. elif symbol in list:
  19. RPN_stack.append(symbol_pop)
  20. comparePriority(symbol, RPN_stack, symbol_stack)
  21. return
  22. elif symbol_pop in list:
  23. symbol_stack.append(symbol_pop)
  24. symbol_stack.append(symbol)
  25. return
  26. else:
  27. continue
  28. symbol_stack.append(symbol_pop)
  29. return
  30. def scanEveryone(input_string, RPN_stack, symbol_stack):
  31. for ch in input_string:
  32. if ch.isdigit():
  33. RPN_stack.append(ch)
  34. else:
  35. if len(symbol_stack) > 0:
  36. if ch == '(':
  37. symbol_stack.append(ch)
  38. elif ch == ')':
  39. while True:
  40. symbol_pop = symbol_stack.pop()
  41. if symbol_pop == '(':
  42. break
  43. else:
  44. RPN_stack.append(symbol_pop)
  45. else:
  46. comparePriority(ch, RPN_stack, symbol_stack)
  47. else:
  48. symbol_stack.append(ch)
  49. def scanInput(RPN_stack, symbol_stack):
  50. input_string = raw_input()
  51. input_string += '#'
  52. scanEveryone(input_string, RPN_stack, symbol_stack)
  53. def calRPN(RPN_stack):
  54. value_stack = []
  55. RPN_stack.append('#')
  56. for value in RPN_stack:
  57. if value == '#':
  58. return value_stack.pop()
  59. break
  60. if value.isdigit():
  61. value_stack.append(value)
  62. else:
  63. right_value = value_stack.pop()
  64. left_value = value_stack.pop()
  65. cal_string = left_value + value + right_value
  66. value_stack.append(str(eval(cal_string)))
  67. def main():
  68. RPN_stack = []
  69. symbol_stack = []
  70. scanInput(RPN_stack, symbol_stack)
  71. print calRPN(RPN_stack)
  72. if __name__ == '__main__':
  73. main()