Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't convert 'int' object to str implicitly: Python 3+

My code is supposed to determine and display the number of binary trees after an input.
I keep getting the can't convert int object to str implicitly error and I have no idea how to fix it. It easily works in versions of Python under 3.0, so please help, as I'm still a beginner in Python and I would like to understand what I'm doing wrong.

import sys
print ("Welcome to Binary Tree Enumeration!")
x = input("Type an integer to output its binary trees: ")
print ("\nYou entered " + str(x))
def distinct(x):
     leafnode = '.'
     dp = []
     newset = set()
     newset.add(leafnode)
     dp.append(newset)
     for i in range(1,x):
         newset = set()
         for j in range(i):
             for leftchild in dp[j]:
                 for rightchild in dp[i-j-1]:
                     newset.add(("(") + leftchild + rightchild + (")"))
         dp.append(newset)
     return dp[-1]
 alltrees = distinct(x+1)
 for tree in alltrees:
     print (tree)
 print ("Thank you for trying this out!")

I forgot to add...this is the error I'm getting.

Traceback (most recent call last):
  File "main.py", line 29, in 
    alltrees = distinct(x+1)
TypeError: Can't convert 'int' object to str implicitly
like image 527
user2860003 Avatar asked Apr 13 '26 14:04

user2860003


1 Answers

As others have suggested, this comes from your call to input. In Python27:

>>> input() + 1
3 # I entered that
4

But using raw_input() (which has the same behaviour as input in Python3+):

>>> raw_input() + 1
3 # I entered that
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

And indeed, we have:

>>> x = raw_input()
3
>>> type(x)
<type 'str'>

In your code, your user-input x is a string, and the code complains on the line distinct(x+1) when you try to add a string and an int. Convert it first like this:

>>> x = int(input())
...
like image 96
val Avatar answered Apr 15 '26 04:04

val



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!