Refactor the following python 3.12 code. Do not use new library's. Focus and reducing…
- User
Refactor the following python 3.12 code. Do not use new library's. Focus and reducing complexity, code duplication and clean code. Only use one line docstrings. Code: import math import tkinter as tk from tkinter import ttk, font as tkFont import ctypes import re
--- Conversion Functions ---
def kg_to_lb(kg): """Convert kilograms to pounds.""" return kg * 2.20462262
def lb_to_kg(lb): """Convert pounds to kilograms.""" return lb / 2.20462262
--- Evaluation Function ---
def evaluate_expression(expression, use_degrees=False): """Safely evaluate a mathematical expression with mode consideration."""
def to_radians(x): """Convert degrees to radians if required.""" return math.radians(x) if use_degrees else x def to_degrees(x): """Convert radians to degrees if required.""" return math.degrees(x) if use_degrees else x def sin(x): return math.sin(to_radians(x)) def cos(x): return math.cos(to_radians(x)) def tan(x): return math.tan(to_radians(x)) def asin(x): try: result = math.asin(x) return to_degrees(result) except ValueError: raise ValueError("asin is only defined for -1 ≤ x ≤ 1") def acos(x): try: result = math.acos(x) return to_degrees(result) except ValueError: raise ValueError("acos is only defined for -1 ≤ x ≤ 1") def atan(x): return to_degrees(math.atan(x)) conversions = {'lb': kg_to_lb, 'kg': lb_to_kg} safe_functions = { 'sqrt': math.sqrt, 'sin': sin, 'cos': cos, 'tan': tan, 'asin': asin, 'acos': acos, 'atan': atan, 'log': math.log10, 'ln': math.log, 'pi': math.pi, 'e': math.e, **conversions } # Replace caret with double asterisk for exponentiation expression = expression.replace('^', '**') # Regular expression to find function calls and their arguments function_pattern = re.compile(r'(\b\w+\b)\(([^)]+)\)') # Validate function arguments for inverse trigonometric functions for func, arg in function_pattern.findall(expression): if func in ['asin', 'acos']: try: value = float(eval(arg, {"__builtins__": None}, safe_functions)) if not -1 <= value <= 1: raise ValueError(f"{func}(x) is undefined for |x| > 1") except Exception as e: return f"Error: {e}" try: result = eval(expression, {"__builtins__": None}, safe_functions) # Normalize very small numbers to zero if isinstance(result, float) and abs(result) < 1e-10: result = 0.0 return round(result, 2) if isinstance(result, (int, float)) else result except Exception as e: return f"Error: {e}"--- Calculator GUI Class ---
class CalculatorGUI: """Tkinter-based Calculator Application with Degrees/Radians toggle."""
def __init__(self, master): self.master = master self.use_degrees = tk.BooleanVar(value=False) self.set_dpi_awareness() self.configure_master() self.create_widgets() self.layout_widgets() self.configure_grid() def set_dpi_awareness(self): """Set DPI awareness for high-DPI displays on Windows.""" try: ctypes.windll.shcore.SetProcessDpiAwareness(1) except Exception: pass def configure_master(self): """Configure the main window properties.""" self.master.title("Calculator") self.master.geometry("1200x720") def create_widgets(self): """Initialize all widgets.""" self.font = tkFont.Font(family="Roboto Flex", size=16) self.expression_var = tk.StringVar() # Entry field for input self.entry = ttk.Entry(self.master, textvariable=self.expression_var, font=self.font, width=50) self.entry.bind("<Return>", self.calculate) # History display self.history_text = tk.Text(self.master, width=70, height=10, font=self.font, wrap="none", state=tk.DISABLED) self.scrollbar = ttk.Scrollbar(self.master, orient="vertical", command=self.history_text.yview) self.history_text.configure(yscrollcommand=self.scrollbar.set) # Degrees/Radians toggle button self.create_toggle_button() # Supported functions and constants supported_info = ( "Functions: sqrt, sin, cos, tan, asin, acos, atan, log, ln\n" "Constants: pi, e\n" "Conversions: lb(kg), kg(lb)" ) self.supported_label = ttk.Label(self.master, text=supported_info, font=self.font) def create_toggle_button(self): """Create and style the Degrees/Radians toggle button.""" style = ttk.Style() style.configure('ToggleButton.TButton', font=self.font, padding=0) # Initial mode is Radians, so button shows "Radians" self.mode_button = ttk.Button( self.master, text="Radians", command=self.toggle_mode, style='ToggleButton.TButton' ) def layout_widgets(self): """Place widgets in the grid.""" # Row 0: Entry field spanning two columns self.entry.grid(row=0, column=0, columnspan=2, padx=5, pady=5, sticky="ew") # Row 1: History text and scrollbar self.history_text.grid(row=1, column=0, padx=5, pady=5, sticky="nsew") self.scrollbar.grid(row=1, column=1, padx=(0,5), pady=5, sticky="ns") # Row 2: Toggle button spanning two columns, aligned to west self.mode_button.grid(row=2, column=0, columnspan=2, padx=5, pady=5, sticky="w") # Row 3: Supported functions and constants label spanning two columns self.supported_label.grid(row=3, column=0, columnspan=2, padx=5, pady=10, sticky="w") def configure_grid(self): """Make the grid layout responsive.""" self.master.columnconfigure(0, weight=1) self.master.columnconfigure(1, weight=0) self.master.rowconfigure(1, weight=1) def toggle_mode(self): """Toggle between Degrees and Radians mode.""" if self.use_degrees.get(): self.use_degrees.set(False) self.mode_button.config(text="Radians") else: self.use_degrees.set(True) self.mode_button.config(text="Degrees") def calculate(self, event=None): """Process the expression and display the result.""" expression = self.expression_var.get().strip() if not expression: return result = evaluate_expression(expression, use_degrees=self.use_degrees.get()) self.display_result(expression, result) self.expression_var.set("") def display_result(self, expression, result): """Show the calculation result in history.""" self.history_text.config(state=tk.NORMAL) mode = "Degrees" if self.use_degrees.get() else "Radians" self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n") self.history_text.config(state=tk.DISABLED) self.history_text.see(tk.END) - Assistant