This method is part of a class that converts inputs from infix to postfix. An example input would be: "11.897/3.4+9.2-0.4*6.9/12.6-16.7="
I have some helper methods below the main method (getPostFix).
I can't understand why the code result += ipop
is causing the error. I use the same code snippets later in the code, so maybe I will have to fix those instances as well. I read some other answers in which the answers seemed to ask the OP - "well what if this function returns False?" But which functions and why would they do that?
def getPostFix(self):
result = ""
# stack used to create postfix string
self.stack = MyStack()
input_string = self.getInput()
input_string_split = [x for x in re.split("(\d*\.?\d*)", input_string) if x != '']
for i in input_string_split:
if isOperand(i):
result += i
elif isOperator(i):
while True:
topItem = self.stack.getTop()
if self.stack.size == 0 or topItem == '(':
self.stack.push(i)
break
else:
precedence_i = getPrecedence(i)
precedence_topItem = getPrecedence(topItem)
if precedence_i > precedence_topItem:
self.stack.push(i)
break
else:
ipop = self.stack.pop()
result += ipop
#result += self.stack.pop()
elif i == '(':
self.stack.push(i)
elif i == ')':
ipop = self.stack.pop()
while ipop != '(':
result += ipop
ipop = self.stack.pop()
elif i == '=':
ipop = self.stack.pop()
result += ipop
#result += self.stack.pop()
while not self.stack.size == 0:
ipop = self.stack.pop()
result += ipop
def isOperand(c):
return c >= '0' and c <= '9'
operators = "+-*/^"
def isOperator(c):
return c in operators
def getPrecedence(c):
result = 0
for i in operators:
result += 1
# because + - and */ have the same value
# these if statements will set their value equal to each other
# for, example when I get to -, the result count is 2, but I subtract 1 to get 1
# which is the same result count as +.
if i == c:
if c in '-/':
result -= 1
break
return result
Here is the error code:
Traceback (most recent call last):
File " ", line 9, in <module>
print(calc)
File " ", line 23, in __str__
theCalc += 'Postfix input is: ' + self.getPostFix() + '\n'
File " ", line 71, in getPostFix
result += ipop
TypeError: can only concatenate str (not "NoneType") to str
Because sometimes you're popping at the end of the iterable and it returns None, try replacing all the lines of
result += ipop
with
result += ipop if ipop else "" # Handles None cases and returns empty string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.