Skip to content

Instantly share code, notes, and snippets.

@beng
Forked from isa/gist:2571012
Last active November 5, 2015 15:13
Show Gist options
  • Save beng/d46645dcc1bcca8da888 to your computer and use it in GitHub Desktop.
Save beng/d46645dcc1bcca8da888 to your computer and use it in GitHub Desktop.
Question: Convert following into the latter data structure in less than 30 lines:
List:
A, B, C
A, C, E
E, F, D
D, A, J
E, D, J
List
A, B, 1 (frequency)
A, C, 2
A, D, 1
A, E, 1
A, J, 1
B, C, 1
C, E, 1
D, E, 2
D, F, 1
D, J, 2
E, F, 1
E, J, 1
from collections import Counter
from itertools import combinations, chain
from operator import itemgetter
rows = [
["A", "B", "C"],
["A", "C", "E"],
["E", "F", "D"],
["D", "A", "J"],
["E", "D", "J"]
]
combos = list(chain(*(map(lambda row: combinations(row, 2), rows))))
result = [(k[0], k[1], v) for k, v in sorted(sorted(Counter(combos).items(), key=itemgetter(1)), key=lambda x: x[0])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment