Jaccard index: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Created Nim solution.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(2 intermediate revisions by 2 users not shown)
Line 252:
+---++---+-----+-----+-----+-----+-----+
</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j">jaccard=. +&# (] %&x: -) [ -&# -.
 
a=. $~ 0
b=. 1 2 3 4 5
c=. 1 3 5 7 9
d=. 2 4 6 8 10
e=. 2 3 5 7
f=. , 8
 
jaccard&.>/~ a ; b ; c ; d ; e ; f</syntaxhighlight>
{{out}}
<pre>┌─┬───┬───┬───┬───┬───┐
│0│0 │0 │0 │0 │0 │
├─┼───┼───┼───┼───┼───┤
│0│1 │3r7│1r4│1r2│0 │
├─┼───┼───┼───┼───┼───┤
│0│3r7│1 │0 │1r2│0 │
├─┼───┼───┼───┼───┼───┤
│0│1r4│0 │1 │1r8│1r5│
├─┼───┼───┼───┼───┼───┤
│0│1r2│1r2│1r8│1 │0 │
├─┼───┼───┼───┼───┼───┤
│0│0 │0 │1r5│0 │1 │
└─┴───┴───┴───┴───┴───┘</pre>
 
=={{header|jq}}==
Line 631 ⟶ 657:
A = [8], B = [8], J = 1
true.
</pre>
 
=={{header|Python}}==
<syntaxhighlight lang="python">
# jaccard_index.py by Xing216
from itertools import product
A = set()
B = {1, 2, 3, 4, 5}
C = {1, 3, 5, 7, 9}
D = {2, 4, 6, 8, 10}
E = {2, 3, 5, 7}
F = {8}
sets = list(product([A, B, C, D, E, F], repeat=2))
set_names = list(product(["A", "B", "C", "D", "E", "F"], repeat=2))
def jaccard_index(set1, set2):
try:
return len(set1 & set2)/len(set1 | set2)
except ZeroDivisionError:
return 0.0
for i,j in sets:
jacc_idx = jaccard_index(i,j)
sets_idx = sets.index((i,j))
print(f"J({', '.join(set_names[sets_idx])}) -> {jacc_idx}")
</syntaxhighlight>
{{out}}
<pre style="height: 10em">
J(A, A) -> 0.0
J(A, B) -> 0.0
J(A, C) -> 0.0
J(A, D) -> 0.0
J(A, E) -> 0.0
J(A, F) -> 0.0
J(B, A) -> 0.0
J(B, B) -> 1.0
J(B, C) -> 0.42857142857142855
J(B, D) -> 0.25
J(B, E) -> 0.5
J(B, F) -> 0.0
J(C, A) -> 0.0
J(C, B) -> 0.42857142857142855
J(C, C) -> 1.0
J(C, D) -> 0.0
J(C, E) -> 0.5
J(C, F) -> 0.0
J(D, A) -> 0.0
J(D, B) -> 0.25
J(D, C) -> 0.0
J(D, D) -> 1.0
J(D, E) -> 0.125
J(D, F) -> 0.2
J(E, A) -> 0.0
J(E, B) -> 0.5
J(E, C) -> 0.5
J(E, D) -> 0.125
J(E, E) -> 1.0
J(E, F) -> 0.0
J(F, A) -> 0.0
J(F, B) -> 0.0
J(F, C) -> 0.0
J(F, D) -> 0.2
J(F, E) -> 0.0
J(F, F) -> 1.0
</pre>
 
Line 823 ⟶ 911:
{{libheader|Wren-fmt}}
Note that the Set object in the above module is implemented as a Map and consequently the iteration order (and the order in which elements are printed) is undefined.
<syntaxhighlight lang="ecmascriptwren">import "./set" for Set
import "./iterate" for Indexed
import "./fmt" for Fmt
9,482

edits