[python-3] TypeError:必须为str,而不是int

Cal*_*vin 3 python parsing binary-tree typeerror python-3.x

我对“ 解析树”代码有疑问。当我尝试用后置订单显示它时,它给我一个错误消息,该错误消息应该是str参数而不是int

from classStack import Stack
from classTree import BinaryTree

def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()

        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent

        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()

        elif i == ')':
            currentTree = pStack.pop()

        else:
            raise ValueError("No se contempla el carácter evaluado")

    return eTree

ParseTree = buildParseTree("( 8 * 5 )")
ParseTree.printPostordenTree(0)
Run Code Online (Sandbox Code Playgroud)

错误:

Traceback (most recent call last):
  File "C:\Users\Franco Calvacho\Downloads\Árboles\parseTree.py", line 38, in <module>
    ParseTree.printPostordenTree(0)
  File "C:\Users\Franco Calvacho\Downloads\Árboles\classTree.py", line 62, in printPostordenTree
    self.getLeftChild().printPostordenTree(n+1)
  File "C:\Users\Franco Calvacho\Downloads\Árboles\classTree.py", line 67, in printPostordenTree
    print("Level: "+ str(n) + " " + self.getRootVal())
TypeError: must be str, not int
[Finished in 0.2s]
Run Code Online (Sandbox Code Playgroud)

这是BinaryTree代码。我清楚地表明,仅BinaryTree代码是可以的,它并没有给我该错误消息。在该代码下,我将您留在python注释中供您查看

class BinaryTree(object):
    def __init__(self, data): 
        self.key = data
        self.leftChild = None 
        self.rightChild = None 

    def insertLeft(self, newNode): 
        if self.leftChild == None:  
            self.leftChild = BinaryTree(newNode) 
        else: 
            t = BinaryTree(newNode) 
            t.leftChild = self.leftChild 
            self.leftChild = t 

    def insertRight(self, newNode): 
        if self.rightChild == None:
            self.rightChild = BinaryTree(newNode)
        else: 
            t = BinaryTree(newNode)
            t.rightChild = self.rightChild
            self.rightChild = t 

    def getRightChild(self):
        return self.rightChild

    def getLeftChild(self):
        return self.leftChild

    def setRootVal(self, obj): 
        self.key = obj

    def getRootVal(self):
        return self.key     

    def printPreordenTree(self, n): 
        if self.getRootVal() != None: 
            print("Level: "+ str(n) + " " + self.getRootVal())
            n+=1 

            if self.getLeftChild() != None:
                self.getLeftChild().printPreordenTree(n) 

            if self.getRightChild() != None:
                self.getRightChild().printPreordenTree(n) 
        return n 

    def printInordenTree(self, n): 
        if self.getRootVal() != None: 
            if self.getLeftChild() != None: 
                self.getLeftChild().printInordenTree(n+1) 

            print("Level: "+ str(n) + " " + self.getRootVal())
            n+=1 

            if self.getRightChild() != None: 
                self.getRightChild().printInordenTree(n) 
        return n 

    def printPostordenTree(self, n):
        if self.getRootVal() != None:
            if self.getLeftChild() != None:
                self.getLeftChild().printPostordenTree(n+1)

            if self.getRightChild() != None:
                self.getRightChild().printPostordenTree(n+1) 

            print("Level: "+ str(n) + " " + self.getRootVal())
            n+=1 
        return n 

"""a = BinaryTree("a")
a.insertLeft("b") 
a.insertRight("c") 
a.getLeftChild().insertLeft("d") 
a.getRightChild().insertLeft("e") 
a.getRightChild().insertRight("f") 
print("Imprimo el árbol de forma Preorden")
a.printPreordenTree(0)
print("\nImprimo el árbol de forma Inorden")
a.printInordenTree(0)
print("\nImprimo el árbol de forma Postorden")
a.printPostordenTree(0)"""
Run Code Online (Sandbox Code Playgroud)

YSe*_*elf 5

print("Level: "+ str(n) + " " + self.getRootVal())
TypeError: must be str, not int
Run Code Online (Sandbox Code Playgroud)

这解释了错误:您只能使用“ +”运算符将字符串追加到字符串,而不是整数。前三个参数是字符串,但self.getRootVal()ist不是。

第一个可能的解决方案:将其强制转换为str,就像使用n以下方法一样:

print("Level: "+ str(n) + " " + str(self.getRootVal()))
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用格式字符串:

print("Level: {} {}".format(n, self.getRootVal()))
Run Code Online (Sandbox Code Playgroud)

后者不需要您将参数强制转换为字符串,并且可读性更好。