Advertisement
Lux-Ferre

Untitled

Apr 24th, 2024
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. def better_calc(self, action):
  2.     message = action["payload"]
  3.     player = message["player"]
  4.     request_source = action["source"]
  5.  
  6.     command = message["parsed_command"]
  7.  
  8.     def parse_input(raw_input: str) -> list:
  9.         pattern = re.compile(r"([+/*-])")
  10.         input_with_spaces = re.sub(pattern, r" \1 ", raw_input)
  11.  
  12.         input_list = input_with_spaces.split()
  13.  
  14.         def is_floatable(n):
  15.             n = n.replace(".", "", 1)
  16.             return n.isnumeric()
  17.  
  18.         converted_list = [float(value) if is_floatable(value) else value for value in input_list]
  19.  
  20.         for value in converted_list:
  21.             if not (isinstance(value, float) or re.search(pattern, value)):
  22.                 raise ValueError
  23.  
  24.         return converted_list
  25.  
  26.     if command['payload'] is not None:
  27.         input_string = command["payload"]
  28.     else:
  29.         return
  30.  
  31.     calculation_map = {
  32.         "*": (lambda a, b: a * b),
  33.         "/": (lambda a, b: a / b),
  34.         "+": (lambda a, b: a + b),
  35.         "-": (lambda a, b: a - b),
  36.     }
  37.  
  38.     parsed_list = parse_input(input_string)
  39.  
  40.     if len(parsed_list) % 2 == 0:
  41.         return
  42.  
  43.     for operator, func in calculation_map.items():
  44.         while operator in parsed_list:
  45.             op_index = parsed_list.index(operator)
  46.  
  47.             a = parsed_list[op_index - 1]
  48.             b = parsed_list[op_index + 1]
  49.  
  50.             if operator == "/" and b == 0:
  51.                 print("Better calc: divide by zero error.")
  52.                 return
  53.             new_value = func(a, b)
  54.  
  55.             parsed_list[op_index - 1] = new_value
  56.             del parsed_list[op_index:op_index + 2]
  57.  
  58.     reply_string = f"{player['username'].capitalize()}, here is the result: {parsed_list[0]}"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement