admin管理员组

文章数量:1026373

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)

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)

Share Improve this question asked Nov 16, 2024 at 17:00 Araz_devpAraz_devp 131 silver badge3 bronze badges 4
  • I haven't read in detail your code yet. But what is clear is that, no, it is not about python sharing the same memory to store identical strings. Maybe CPython does so (it's an implementation problem, so it probably depend on the interpreter more than on the language). After all, even C compilers may do so (for constant "hard-coded" strings). But the same reason that makes me think "maybe CPython does that indeed" also makes me sure that this cannot be the reason: python strings are unmutable. – chrslg Commented Nov 16, 2024 at 17:14
  • And the fact that they are makes indeed possible and quite easy for an interpreter to just share the same memory each times it sees an already seen string. But that fact also makes impossible what you suspect: it cannot be because you modified a string and that modify also all other formerly identical strings, since you cannot modify a string. The line of code you quoted show clearly that you build a new string. So it doesn't impact any existing string (even not the old one, that will probably be soon garbage collected) – chrslg Commented Nov 16, 2024 at 17:17
  • Check that the minus sign in re.split("[÷×+–]",current_text) is actually what you expect. It is not the minus sign I would expect. For example, try: print("–" == "-") where the first is the character from your code and the second is what I would type on my keyboard. – JonSG Commented Nov 16, 2024 at 17:17
  • I have not gone through your code in detail, but given your description and the fact that you use str.replace() i'm guessing that you expect that to work only on the first character. see How to replace the first character alone in a string using python? – JonSG Commented Nov 16, 2024 at 17:27
Add a comment  | 

1 Answer 1

Reset to default 1

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)

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)

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)

Share Improve this question asked Nov 16, 2024 at 17:00 Araz_devpAraz_devp 131 silver badge3 bronze badges 4
  • I haven't read in detail your code yet. But what is clear is that, no, it is not about python sharing the same memory to store identical strings. Maybe CPython does so (it's an implementation problem, so it probably depend on the interpreter more than on the language). After all, even C compilers may do so (for constant "hard-coded" strings). But the same reason that makes me think "maybe CPython does that indeed" also makes me sure that this cannot be the reason: python strings are unmutable. – chrslg Commented Nov 16, 2024 at 17:14
  • And the fact that they are makes indeed possible and quite easy for an interpreter to just share the same memory each times it sees an already seen string. But that fact also makes impossible what you suspect: it cannot be because you modified a string and that modify also all other formerly identical strings, since you cannot modify a string. The line of code you quoted show clearly that you build a new string. So it doesn't impact any existing string (even not the old one, that will probably be soon garbage collected) – chrslg Commented Nov 16, 2024 at 17:17
  • Check that the minus sign in re.split("[÷×+–]",current_text) is actually what you expect. It is not the minus sign I would expect. For example, try: print("–" == "-") where the first is the character from your code and the second is what I would type on my keyboard. – JonSG Commented Nov 16, 2024 at 17:17
  • I have not gone through your code in detail, but given your description and the fact that you use str.replace() i'm guessing that you expect that to work only on the first character. see How to replace the first character alone in a string using python? – JonSG Commented Nov 16, 2024 at 17:27
Add a comment  | 

1 Answer 1

Reset to default 1

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)

本文标签: Issue with Toggling Sign of the Last Entered Number in Calculator Using ⁺∕₋ in PythonStack Overflow