pythonpython-recustomtkinter

Issue with Toggling Sign of the Last Entered Number in Calculator Using ⁺∕₋ in Python


I am developing a calculator using Python. The problem I'm facing is that when I try to toggle the sign of the last number entered by the user using the ⁺∕₋ button, all similar numbers in the text get toggled as well. I believe the reason for this is Python's memory optimization, which causes similar strings to be stored only once in memory and their addresses to be used multiple times in the list.

code:

import re, math
from decimal import Decimal
from fractions import Fraction
from customtkinter import *

...

    def on_button_click(self, char:str):

        if char == "✔":
            # self.buttons_dict[char].configure(text="")
            ...
        elif char == 'C':
            self.entry.delete(0, END)
        elif char == 'CE':
            self.entry.delete(0, END)
        elif char == 'Del':
            current_text = self.entry.get()
            self.entry.delete(0, END)
            self.entry.insert(END, current_text[:-1])
        elif char == '⁺∕₋':
            current_text = self.entry.get()
            current_text_list = [(item+' ')[:-1] for item in re.split("[÷×+–]",current_text)]
            for i in current_text_list:
                print(id(i))
            if current_text:
                print(current_text_list)
                if current_text_list[-1][0] == '(':
                    self.entry.delete(0, END)
                    if len(current_text_list) > 1:
                        last_txt = current_text_list[-1]
                        current_text_list[-1] = current_text_list[-1][2:].replace(")", "")
                        self.entry.insert(END, current_text.replace(last_txt,current_text_list[-1]))
                    else:
                        self.entry.insert(END, current_text.replace(current_text_list[-1], current_text_list[-1].replace("-", "")))
                else:
                    self.entry.delete(0, END)
                    if len(current_text_list) > 1:
                        self.entry.insert(END, current_text.replace(current_text_list[-1], f"(-{current_text_list[-1]})"))
                    else:
                        self.entry.insert(END, current_text.replace(current_text_list[-1], f"-{current_text_list[-1]}"))

        elif char == '=':
            self.buttons_dict[char].configure(text="✔")
            try:
                expression = self.entry.get().replace('x', '*')
                result = eval(expression.replace('×', '*').replace("÷", '/'))
                if isinstance(result, float):
                    result_decimal = Decimal(result).quantize(Decimal('0.01'))
                    if math.isclose(result, float(Fraction(result_decimal))):
                        display_result = result_decimal
                    else:
                        display_result = f"{result_decimal}..."
                else:
                    display_result = result
                self.entry.delete(0, END)
                self.entry.insert(END, str(display_result))
            except Exception as e:
                self.entry.delete(0, END)
                self.entry.insert(END, 'Error')
        else:
            current_text = self.entry.get()
            self.entry.delete(0, END)
            self.entry.insert(END, current_text + char)

Solutions I tried but didn't work:

current_text_list = [(item+'.')[:-1] for item in re.split("[÷×+–]", current_text)]

current_text_list = re.split("[÷×+–]", current_text)
current_text_list[-1] = (current_text_list[-1]+'.')[:-1]

new_current_text_list = [str(i) for i in current_text_list]

copied_list = copy.deepcopy(current_text_list)

The result of all in the test:

Input: 2 × 2

After pressing the ⁺∕₋ button:

Result: (-2) × (-2)


Solution

  • replace() method replaces all of the occurrences of a substring, not just the last one. So when the following line executes:

    current_text.replace(current_text_list[-1], ...)
    

    It replaces all instances of current_text_list[-1] in current_text. That's why 2 x 2 is becoming (-2) x (-2), both 2s being are replaced.

    A possible solution could be to split the expression in the tokens (numbers and operators). Then only modify the last number, and then you could reconstruct the expression.

    tokens = re.split('([÷×+–])', current_text)
    tokens = [t for t in tokens if t] # Removing the empty strings
    last_number = tokens[-1]
    if last_number.startswith('(-'):
        last_number = last_number[2:-1]
    else:
        last_number = f"(-{last_number})"
    tokens[-1] = last_number
    
    # Finally reconstruct the whole expression
    new_text = ''.join(tokens)
    self.entry.delete(0, END)
    self.entry.insert(END, new_text)