Cannot fix mixed operand in python - python

I am creating a program in which compresses text, which includes normal letters and punctuation and etc. However I have come across a mixed operand Type error of some sort and I do not know how to fix this. I have tried reading other posts about the topic but I cannot understand how it works and how to apply this to my code.
print("The compression program has started")
myDict={}
revDict={}
sentList=[]
posList=[]
num = 0
sentence = open("pyCompress.txt","r").read().split()
for word in sentence:
if word not in myDict:
myDict[word] = num
num += 1
print(sentence)
print(myDict)
for k, v in myDict.items():
revDict[v] = k
file = open("Positions.txt","w")
for word in sentence:
file.write((myDict[word]) + " ")
file.close()
There is more code beyond these lines
The error I get is: TypeError: unsupported operand type(s) for +: 'int' and 'str'

Cast the myDict[word] to a str so you can perform the concatenation, as well as move the file.close outside the loop as mentioned by others. Thus, only changing the last loop like this should fix the errors you're getting:
for word in sentence:
file.write((str(myDict[word]) + " "))
file.close()

Python does not allow adding integers to strings:
>>> 1 + "a"
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
1 + "a"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
To put the number into the string you can either explicitly convert it:
>>> str(1) + "a"
'1a'
Or format it in with either the % notation or {} notation:
>>> "the number %d is prime"%874193
'the number 874193 is prime'
>>> "please give me {n} apples".format(n=2)
'please give me 2 apples'
You could also use print to handle the conversion for you:
print(myDict[word], file = file, end=" ")
Next you need to make sure you close a file after writing all the data that needs to be written to it, in your case that would be after the for loop:
for word in sentence:
print(myDict[word], file = file, end=" ")
file.close() #un-indent
Although you may want to use a with statement to ensure the file is properly handled:
with open("Positions.txt","w") as file:
for word in sentence:
print(myDict[word], file = file, end=" ")
assert file.closed #the file is closed at the end of with block

try this, read my comments for the changes I've made
print("The compression program has started")
myDict={}
revDict={}
sentList=[]
posList=[]
num = 0
sentence = open("pyCompress.txt","r").read().split()
for word in sentence:
if word not in myDict:
# needs to convert to str
# also indentation problem here
myDict[word] = str(num)
num += 1
print(sentence)
print(myDict)
for k, v in myDict.items():
revDict[v] = k
file = open("Positions.txt","w")
for word in sentence:
file.write((myDict[word]) + " ")
# indentation problem here
file.close()
In case you want to write both keys and values into the file, try this,
file.write(word + ":" + myDict[word] + " ")

Related

unsupported operand types error in python 3.x when trying to operate on lists

Assuming all ASCII codes are set to variables (a = 97, b = 98, etc).
word = eval(input("What would you like to say? "))
key = 174
print (word)
changedword = (', '.join(str(I + key) for I in word))
print ("Your encrypted string is:" + changedword)
ans1 = input("Would you like to decrypt this?")
print (ans1)
if (ans1 == "yes"):
print (changedword)
decryptedword = (', '.join(str(I - key) for I in changedword))
ans2 = input(decryptedword + " was your decrypted number list. Do you
want to translate to ASCII code?")
if (ans2 == "yes"):
print (', '.join(str(chr(I)) for I in decryptedword))
When running this code I get the error
TypeError: unsupported operand type(s) for -: 'str' and 'int'
in reference to line 11
I am aware that str and int are different, but it worked the first time I used it and I'm not sure how to fix the problem. Any help would be greatly appreciated.
I know that it references encryption a lot, and I know that it's not really an encryption, but I'm new to this and I'm just playing around.
All the extra printing was for my own testing.
Like you said in the question the problem line is:
decryptedword = (', '.join(str(I - key) for I in changedword))
key is an int, but changedword is a str from this line:
changedword = (', '.join(str(I + key) for I in word))
You iterate through changedword for I in changedword and Thus I is also a str type.
So your problem is here I - key when you try to subtract an int from a str.
If you want to use the ascii value to add and subtract use the function ord(c) where c is a single character in a string. When you want to convert it back to a character use the function chr(a) where a is an ascii int

myFile.write(item+"\n") TypeError: unsupported operand type(s) for +: 'int' and 'str'

Getting error:
myFile.write(item+"\n") TypeError: unsupported operand type(s) for +:
'int' and 'str'
and not sure why. Where shall I add the int? This is my code
#comment program to create a list in a file
numberList = []
for counter in range (1,7):
number = int(input("choose a number")) #asks user to enter 6 numbers
numberList.append(number) #stores the numbers in a list
#writes numbers to a file
myFile = open('numbers.txt','w')
for item in numberList:
myFile.write(item+"\n")
myFile = open('numbers.txt','rt')
contents = myFile.read()
print(contents)
numSum = sum(numberList)
print(numSum)
sumTimesSum = sum * sum
average = SumTimesSum / 6
print(average)
myFile.close()
numberList is a list of int and when you write to a text file, you must convert it to string, so:
for item in numberList:
myFile.write(str(item)+"\n")
Or without using for loop
s = '\n'.join(map(str, numberList))
myFile.write(s)
It's literally trying to add the string and the number (i.e. 1 + 2 = 3, "abc" + 1 = ???). You need to convert the number to a string.
myFile.write(str(item) + "\n")
You could also use string formatting.
myFile.write("%d\n" % item)
I believe that you need to make item a string.
myFile.write(+str(item)+"\n")

Python Reading List From File And Printing Back In Idle Error

When I try to read from a file, I'm getting an annoying error, I think it's got something to do with the list format of the variables but I'm not sure.
If anyone can help with with this issue that would be great.
I think it's also got something to do with \n being printed at the end of the list.
This is my code:
Option 1
def one():
print ("")
print ("You have chosen to read the file!")
print ("")
file = open("sentence.txt" , "r")
words = file.readlines(1)
nums = file.readlines(2)
#Remove "\n"
#This bit doesn't work, I'm not sure how to remove "\n"
#These were me trying to get rid of the "\n"
#map(str.strip, words)
#words = words.strip('\n')
print(words)
print (nums)
print ("")
#Reconstruct sentence here
What file.readlines(1) returns is a single element list, and the element is a string. What you want to do get the string itself and replace the '\n', '[', ']', etc.
Try
words[0].strip("\n][").replace("'", "").split(",")
The function file.readlines() does not take an argument for the number of lines, it reads all the lines of the file at once. (for the record, if you do pass an argument like file.readlines(n), the argument n is a "hint" about the number of bytes to read...more info here at Python's function readlines(n) behavior)
def one():
print ("")
print ("You have chosen to read the file!")
print ("")
file = open("sentence.txt" , "r")
lines = file.readlines() # read all the lines into a list
words = lines[0]
nums = lines[1]
#Remove "\n"
#This bit doesn't work, I'm not sure how to remove "\n"
#These were me trying to get rid of the "\n"
#map(str.strip, words)
words = words.strip("\n][").replace("'", "").split(",")
nums = nums.strip("\n][").replace("'", "").split(",")
nums = list(map(int, numbers)) ## assuming you want to convert the string to integers, use this
print(words)
print (nums)
print ("")
#Reconstruct sentence here
remade_sentence = ' '.join([words[i-1] for i in nums]) ## changed empty string to space to add spaces
print (remade_sentence)
file.close() ## also, make sure to close your file!
EDIT: I have updated the code to deal with nums being a list of strings.
EDIT 2: updating code to reflect #notevenwrong's method of removing brackets and quotes
EDIT 3: Resimplifying...when I open my input file in a text editor, I literally see:
['the', 'dog', 'cat']
[1, 1, 1, 2, 1, 3]
If that is not the right input, then this code may not work.
You are getting exception at [words[i-1], Because i is str and you can perform -: 'str' and 'int'.
>>> i = '1'
>>> i -1
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
i -1
TypeError: unsupported operand type(s) for -: 'str' and 'int'
A quick fix should be-
remade_sentence = ''.join([words[int(i)-1] for i in nums])

Typecasting a String into an Int within a for loop

How would I store the position variable i as an int so that I can play with that particular position within a string.
sentence = input()
for i in sentence:
if i == " ":
j = int(i) #this line is throwing an error
print (sentence[0:j])
There are two flaws within your code:
if i == " ":
j = int(i)
So you check whether i is a space character, in which case you want to convert that space into a number. Of course that’s not going to work—what number is that space supposed to mean?
The other flaw is the reason why you have a space character there. You say that you want to use the position, or index, of the character. But your for loop does something different than what you expect: for x in sequence will iterate over every element x within that sequence. In case of a string sequence, you will get every character—not an index though.
For example:
>>> for x in 'foo':
print(x)
f
o
o
As you can see, it prints the characters, not the indexes.
You can use enumerate() for this though. Enumerate will enumerate over a sequence giving you the value and the index it appeared at:
>>> for i, x in enumerate('foo'):
print(i, x)
0 f
1 o
2 o
So you get the index too.
In your case, your code would look like this then:
sentence = input()
for i, x in enumerate(sentence):
if x == " ":
print(sentence[0:i])
If You try to find position of ' ' use sentence.index(' '):
sentence = input()
try:
i = sentence.index(' ')
print (sentence[0:j])
except ValueError:
pass
You should use enumerate
for k, v in enumerate(sentence):
if v == " ":
print (sentence[0:k])
You are casting space char to int. Of course does not work.
>>> int(' ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

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
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())
...
In order to concatenate strings and string representations of various types, you have to cast the latter to strings explicitly, e. g.
"(" + str(leftchild) + ", " + str(rightchild) + ")"
or, more readably,
"(%i, %i)" % (leftchild, rightchild)
By default when you use input its always a string input
x = input("Type an integer to output its binary trees: ")
print ("\nYou entered " + str(x))
So there's no need to convert it again !
and here use .format()
newset.add("{0} {1} {2} {3}".format(r"(", leftchild, rightchild, r")"))
But the above one will not maintain the datastructure !!
If you would like to preserve the datastructure, use,
newset.add(tuple(leftchild, rightchild))

Categories