Skip to content

Instantly share code, notes, and snippets.

@loisaidasam
Forked from isa/gist:2571012
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loisaidasam/35805ef953368683f4ff to your computer and use it in GitHub Desktop.
Save loisaidasam/35805ef953368683f4ff 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 itertools import combinations
x = [('a', 'b', 'c'), ('a', 'c', 'e'), ('e', 'f', 'd'), ('d', 'a', 'j'), ('e', 'd', 'j')]
counts = {}
for row in x:
for combo in combinations(row, 2):
combo = tuple(sorted(combo))
counts[combo] = counts.get(combo, 0) + 1
result = [(combo[0], combo[1], count) for combo, count in sorted(counts.iteritems(), key=lambda item: item[0])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment