Advertisement
Guest User

rick ross breat

a guest
Mar 20th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.20 KB | None | 0 0
  1. import ast
  2. import os
  3.  
  4.  
  5. class Empty(Exception):
  6. pass
  7.  
  8.  
  9. class Stack:
  10.  
  11. def __init__(self):
  12. self._data = []
  13.  
  14. def __len__(self):
  15. return len(self._data)
  16.  
  17. def __str__(self):
  18. return str(self._data)
  19.  
  20. def is_empty(self):
  21. return len(self._data) == 0
  22.  
  23. def push(self, e):
  24. self._data.append(e)
  25.  
  26. def top(self):
  27. if self.is_empty():
  28. raise Empty('Stack is empty')
  29. return self._data[-1]
  30.  
  31. def pop(self):
  32. if self.is_empty():
  33. raise Empty('Stack is empty')
  34. return self._data.pop()
  35.  
  36.  
  37. def string_check(string):
  38. parentheses_stack = Stack()
  39. parentheses_count = 0
  40. operators_count = 0
  41. operands_count = 0
  42.  
  43. try:
  44. for lexeme in string:
  45. if lexeme == '(':
  46. parentheses_stack.push('(')
  47. parentheses_count += 1
  48. elif lexeme == ')':
  49. parentheses_stack.pop()
  50. elif lexeme in [str(a) for a in range(0, 10)]:
  51. operands_count += 1
  52. elif lexeme in ['+', '-', '*', '/']:
  53. if parentheses_stack.is_empty():
  54. print('Not a valid expression, brackets mismatched.')
  55. return False
  56. operators_count += 1
  57. except Empty:
  58. print('Tried to close parenthesis which was not open')
  59. return False
  60. if not parentheses_stack.is_empty(): # there are open brackets
  61. print('Not a valid expression, brackets mismatched.')
  62. return False
  63. if operators_count + 1 < operands_count:
  64. print('Not a valid expression, operator missing.')
  65. return False
  66. if parentheses_count != operators_count:
  67. print('Not a valid expression, wrong number of operands.')
  68. return False
  69.  
  70. return True
  71.  
  72.  
  73. def input_correct_expression():
  74. mathematical_expression = input("\nEnter a mathematical expression: ")
  75. while not string_check(mathematical_expression):
  76. mathematical_expression = input("\nEnter a VALID mathematical expression: ")
  77. return mathematical_expression
  78.  
  79.  
  80. def eval_expression(expression):
  81. print("\n" + str(expression) + " = " + str(eval(expression)))
  82. with open('cache.txt', 'w+') as file_cache:
  83. file_cache.write("")
  84. # Flushes cache.txt out of its contents once a new expression is entered
  85.  
  86.  
  87. def show_children(node, level=0):
  88. def print_operator(operator, lvl):
  89. operator = str(operator)
  90. print((lvl - 2) * " ", operator)
  91. with open('cache.txt', 'a+') as file_cache:
  92. file_cache.write((lvl - 2) * " " + " " + operator + "\n")
  93.  
  94. if isinstance(node, ast.Num):
  95. num_node = (level + 2) * " " + " --" + str(node.n)
  96. print(num_node)
  97. with open('cache.txt', 'a+') as file:
  98. file.write(str(num_node) + '\n')
  99.  
  100. else:
  101. if "Add" in str(node):
  102. print_operator("-- +", level)
  103. elif "Sub" in str(node):
  104. print_operator("-- -", level)
  105. elif "Div" in str(node):
  106. print_operator("-- /", level)
  107. elif "Mul" in str(node):
  108. print_operator("-- *", level)
  109. elif "BinOp" in str(node) or "Expression" in str(node):
  110. pass
  111. else:
  112. print(level * " ", end=" ")
  113. print(str(node))
  114.  
  115. for child in ast.iter_child_nodes(node):
  116. show_children(child, level + 4)
  117.  
  118.  
  119. def draw_tree(expression):
  120. print("\n\nBinary tree of the expression '" + str(expression) + "':\n")
  121. show_children(ast.parse(expression, "", "eval"))
  122.  
  123.  
  124. def save(content):
  125. if content not in open('saved_expressions.txt').read():
  126. choice = None
  127. print("\nDo you want to save " + str(content) + " in saved_expressions.txt?")
  128. while choice not in ['y', 'n']:
  129. choice = input("y/n: ", )
  130. if choice == 'y':
  131. with open('saved_expressions.txt', 'a+') as file:
  132. file.write(str(content) + '\n')
  133. else:
  134. pass
  135. print('\n' + '-' * 64)
  136.  
  137.  
  138. def load():
  139. if os.stat('saved_expressions.txt').st_size != 0:
  140.  
  141. print("\nWould you like to load a saved expression?")
  142. choice = None
  143.  
  144. while choice not in ['y', 'n']:
  145. choice = input("y/n: ", )
  146. print()
  147.  
  148. if choice == 'n':
  149. return input_correct_expression()
  150.  
  151. else:
  152. print("0 - Cached expression")
  153.  
  154. lines_list = open('saved_expressions.txt').read().splitlines()
  155. for index, filename in enumerate(lines_list):
  156. print(index + 1, "-", filename)
  157.  
  158. file_number = None
  159. while file_number not in range(-1, len(lines_list)):
  160. file_number = int(input("\nEnter a number: ")) - 1
  161.  
  162. if file_number == -1:
  163. cached_list = open('cache.txt').read().splitlines()
  164. for line in cached_list:
  165. print(line)
  166. run()
  167.  
  168. return lines_list[file_number]
  169.  
  170. else:
  171. return input_correct_expression()
  172.  
  173.  
  174. def run():
  175. exp = load()
  176.  
  177. eval_expression(exp)
  178.  
  179. draw_tree(exp)
  180.  
  181. save(exp)
  182.  
  183.  
  184. while True:
  185. run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement