'Need some help on an algebra calculator
I want a fully functioning calculator where you put in things like 1+2 or 1*2 or 1+a or 1*a, that sort of thing. However I am having some trouble when combining + and *. Any ideas how I could improve it?
What I have so far (sorry about the messy and unnecessary conversions from str to int and back):
class Math:
def Calculate(stuff):
result = 0
resultstr = ""
if "*" in stuff:
y = stuff.split("*")
for x in y:
if result == 0:
result = x
else:
try:
x = int(x)
except:
result = str(result) + x
result = result.replace("0*", "")
result = result.replace("*0", "")
else:
try:
result = int(result) * int(x)
except:
resultstr = str(result)
result = x
if "+" in stuff:
y = stuff.split("+")
for x in y:
try:
x = int(x)
except:
result = str(result) + "+" + x
result = result.replace("0+", "")
result = result.replace("+0", "")
else:
try:
result = int(result) + int(x)
except:
resultstr = str(result) + "+"
result = x
finalresult = str(resultstr)+str(result)
print(str(finalresult))
h = Math
h.Calculate("a*5+5")
Solution 1:[1]
Take the example you just gave (a*5+5). If I understand exactly your program, it will find that "stuff" contains *, so it will divide it into x=a and y=5+5. By doing so, you're assigning 5+5 to result which I don't think it's what you want to do.
PS: Little piece of advice: Try to name your variables in an understandable way. For example, I would call stuff something like query.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | blackbrandt |
