Question

I have a list of ints (hitTableWord) and I am trying to add 1 over the absolute value of the numbers for the whole list and I keep getting this error message in python: metric = metric + 1/(abs(metricNumber)) TypeError: unsupported operand type(s) for +: 'type' and 'float'. metric was initialized as: metric = 0

Thing is I am a rookie programmer and don't know what it means.

 for a in range (0, len(hitTableWord)):
         output_file.write('Hit Word: '+ str(hitTableWord[a]) +' ' + str(hitTableNear[a])+ ', ')
         metric = metric + 1/(abs(hitTableWord[a]))

Any help would be appreciated. As usual with my questions I am sure it is something ridiculously simple that I just do not know about. So thanks for all your patience.

Was it helpful?

Solution

It seems like metric is a class you have defined somewhere, rather than an instance - ie, you have something like:

class metric(object):
    pass

You would need to call metric() to get an instance of it. Note that you'll continue to get a very similar error if metric doesn't define __add__.

Likewise, you may have inadvertently done:

metric = someclass

when you meant:

metric = someclass()

Either way, the error message is saying that metric contains a class, and Python doesn't know how to add classes to floats (or, for that matter, to anything much).

Also:

for a in range (0, len(hitTableWord)):

Is something you usually don't need to do in Python. Here you're using it because you need to access the relevant element of both hitTableWord and hitTableNear - you can do this more idiomatically as:

for word, near in zip(hitTableWord, hitTableNear):

OTHER TIPS

I'm assuming that hitTableWord only contains numbers, can you take a look at where you define metric? The error means that you are trying to add two different types of variables together, and that Python can not perform this operation for the given types, similar to how you can not add strings to integers, or concatenate integers to strings.

As an example:

5 + "abc" 

Here, the plus works as arithmetic operator, this does not work with strings.

"abc" + 5  

Here, the plus indicates string concatenation, this does not work with integers.

You write that metric with initialized with 0. But I suppose that it is not so. You have a value of type type in the metric variable. And that is the problem here.

How about

from itertools import izip

metric = 0.
for tw,tn in izip(hitTableWord, hitTableNear):
    output_file.write("Hit Word: {} {}".format(tw,tn))
    metric += 1./abs(tw)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top