Abdel-Rahman Shoman Abdel-Rahman Shoman - 3 days ago 3
Python Question

python: Arithmetic operation on tuple results in TypeError

So I have two different 2-dimensional arrays

words
and
scores


words
is a 2-dimensional array of strings
scores
is a 2-dimensional array of float

I convert them into tuples and perform arithmetic operations on them (I originally pass the tuples to a library that does that, but for simplicity I copied the operation and started testing on it)

My code

for i in range(0,len(scores)):
freqs = []
for word, score in zip(words[i], scores[i]):
freqs.append((word, score))
frequencies = [ (word, freq / 20.0) for word, freq in freqs ]


when I run this code I get the following error

TypeError Traceback (most recent call last)
<ipython-input-17-017692219adb> in <module>()
4 for word, score in zip(words[i], scores[i]):
5 freqs.append((word, score))
----> 6 frequencies = [ (word, freq / 20.0) for word, freq in freqs ]
7
8 #elements = wc.fit_words(freqs)

TypeError: unsupported operand type(s) for /: 'str' and 'float'

Answer

freq is a string. convert to a float before division.

eg: float(freq)

so new code will be frequencies = [ (word, float(freq) / 20.0) for word, freq in freqs ]

Comments