No Description

tt.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #recusion call
  21. comparePriority(symbol, RPN_stack, symbol_stack)
  22. return
  23. elif symbol_pop in list:
  24. symbol_stack.append(symbol_pop)
  25. symbol_stack.append(symbol)
  26. return
  27. else:
  28. continue
  29. symbol_stack.append(symbol_pop)
  30. return
  31. def scanEveryone(input_string, RPN_stack, symbol_stack):
  32. for ch in input_string:
  33. if ch.isdigit():
  34. RPN_stack.append(ch)
  35. else:
  36. if len(symbol_stack) > 0:
  37. if ch == '(':
  38. symbol_stack.append(ch)
  39. elif ch == ')':
  40. while True:
  41. symbol_pop = symbol_stack.pop()
  42. if symbol_pop == '(':
  43. break
  44. else:
  45. RPN_stack.append(symbol_pop)
  46. else:
  47. comparePriority(ch, RPN_stack, symbol_stack)
  48. else:
  49. symbol_stack.append(ch)
  50. def scanInput(RPN_stack, symbol_stack):
  51. input_string = raw_input()
  52. input_string += '#'
  53. scanEveryone(input_string, RPN_stack, symbol_stack)
  54. def calRPN(RPN_stack):
  55. value_stack = []
  56. RPN_stack.append('#')
  57. for value in RPN_stack:
  58. if value == '#':
  59. return value_stack.pop()
  60. break
  61. if value.isdigit():
  62. value_stack.append(value)
  63. else:
  64. right_value = value_stack.pop()
  65. left_value = value_stack.pop()
  66. cal_string = left_value + value + right_value
  67. value_stack.append(str(eval(cal_string)))
  68. def main():
  69. RPN_stack = []
  70. symbol_stack = []
  71. scanInput(RPN_stack, symbol_stack)
  72. print calRPN(RPN_stack)
  73. if __name__ == '__main__':
  74. main()