1+ from enum import Enum
2+
3+ class Operator (Enum ):
4+ ADD = "+"
5+ SUBTRACT = "-"
6+ MULTIPLY = "x"
7+ DIVIDE = "/"
8+
9+ ALL_CLEAR = "AC"
10+ CLEAR_ENTRY = "CE"
11+ FLIP_SIGN = "+/-"
12+ DECIMAL = "."
13+ EQ_SIGN = "="
14+
115class Calculator :
216 def __init__ (self ):
317 self .equation_first = ""
@@ -8,26 +22,51 @@ def __init__(self):
822 def input_button (self , button : str ):
923 if button .isdigit ():
1024 self .add_digit (button )
11- elif button in [ "+" , "-" , "/" , "x" ] :
25+ elif button in set ( item . value for item in Operator ) :
1226 self .set_operator (button )
13- elif button == "=" :
27+ elif button == EQ_SIGN :
1428 if self .current_part == "last" :
1529 self .solve ()
16- elif button == "." :
30+ elif button == DECIMAL :
1731 self .add_decimal ()
18- elif button == "+/-" :
32+ elif button == FLIP_SIGN :
1933 self .flip_sign ()
34+ elif button == ALL_CLEAR :
35+ self .all_clear ()
36+ elif button == CLEAR_ENTRY :
37+ self .clear_entry ()
2038
39+ def set_equation (self , first_part : str | float | int , operator : Operator = None , second_part : str | float | int = "" ):
40+ self .equation_first = str (first_part )
41+ self .equation_type = operator or ""
42+ self .equation_last = str (second_part )
43+ if operator == None :
44+ self .current_part = "first"
45+ else :
46+ self .current_part = "last"
47+
48+ def clear_entry (self ):
49+ if self .current_part == "first" :
50+ self .equation_first = self .equation_first [:- 1 ]
51+ elif self .current_part == "last" :
52+ if self .equation_last == "" :
53+ self .equation_type = ""
54+ self .current_part = "first"
55+ else :
56+ self .equation_last = self .equation_last [:- 1 ]
57+
58+ def all_clear (self ):
59+ self .set_equation ("" )
60+
2161 def add_digit (self , digit ):
2262 if self .current_part == "first" :
2363 self .equation_first += digit
2464 elif self .current_part == "last" :
2565 self .equation_last += digit
2666
27- def set_operator (self , operator ):
67+ def set_operator (self , operator : Operator ):
2868 self .equation_type = operator
29- if self .current_part == "first" :
30- self .current_part = "last"
69+ self .current_part = "last"
3170
3271 def flip_sign (self ):
3372 if self .current_part == "first" :
0 commit comments