I'm trying to make a loop that turn a function (like f(x)=(2x+3)(2x-3)) into a better format for editing, simply by adding a '+' before numbers (it would become f(x)=(+2x+3)(+2x-3)). The problem is that in the loop, after I insert a new char in the middle of the string, the string doesn't update, so when the loop goes on and I try to access a certain index of the function string, the char isn't correct.
def rewriteFunction(function): for i, c in enumerate(function): newFunction += c if(str(c).isdigit()): if not(i == 0): if not(Sign.isSign(function[i - 1])): function = function[:i] + "+" + function[i:]
If possible, could you answer me by sending the exact (corrected) code, without modifying it too much, of course if that's the right method to do that. Thanks in advance!!
In one line you store your updated data in the variable
newFunction, but in another you store your updates back into
function. For consistency, let's never change
functionand apply all of our updates to
You never initialize
You never explicitly return anything from
def rewriteFunction(function): newFunction = '' for i, c in enumerate(function): if(str(c).isdigit()): if not(i == 0): if not(function[i - 1] in '+-'): newFunction += '+' newFunction += c return newFunction assert rewriteFunction('f(x)=(2x+3)(2x-3)') == 'f(x)=(+2x+3)(+2x-3)'