Search code examples
pythonpycharmtypeerror

Creating a function that calculates the Sørensen-Dice coefficient in python


In my Python class I have to create a function for calculating the Sorensen-Dice coefficient. The Formular is: 2|X ∩ Y|/ |X| + |Y| Ive been trying for hours but I just can't get it right. This is what I got so far. Might be completely on the wrong path tho, Im a total beginner.

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
def dice(a, b):
    _a = set(a)
    _b = set(b)
    return (2*_a.intersection(_b)) / ((_a) + (_b))
dice(a, b)

The error I get is: TypeError: unsupported operand type(s) for *: 'int' and 'set'

Thanks!


Solution

  • There is a very small bug in your code. In the return line, you need to use the size of the sets. The coefficient is about the size of the set.

    So use return (2*len(_a.intersection(_b))) / (len(_a) + len(_b)).

    Edit -

    How I debugged the code: The error says TypeError: unsupported operand type(s) for *: 'int' and 'set', which is an error about the multiplication operator you are using.

    Edit 2 - typos