Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading