Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[python-3]TypeError: must be str, not int

I have a problem with the Parse Tree code. When I try to show it with post-order, it gives me an error message that should be str the parameter and not 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)

Error:

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]

Here's the BinaryTree code. I make it clear that the BinaryTree code alone is OK and it doesn't give me that error message. Under that code I leave you in python comments for you to see.

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)"""
like image 776
calvin11 Avatar asked Aug 29 '26 11:08

calvin11


1 Answers

print("Level: "+ str(n) + " " + self.getRootVal())
TypeError: must be str, not int

This explains the error: You can only append strings to strings using the "+" operator, not integers. The first three arguments are strings, but self.getRootVal() ist not.

First possible solution: Cast it to str, like you did with n:

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

Or you can use format strings:

print("Level: {} {}".format(n, self.getRootVal()))

The latter does not require you to cast the arguments to strings, and may be better readable.

like image 102
YSelf Avatar answered Sep 01 '26 01:09

YSelf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!