Skip to content

Instantly share code, notes, and snippets.

@mazieres
Created March 19, 2015 14:02
Show Gist options
  • Save mazieres/eab33c4aeae916e33acd to your computer and use it in GitHub Desktop.
Save mazieres/eab33c4aeae916e33acd to your computer and use it in GitHub Desktop.
import unittest
class TestExtract(unittest.TestCase):
def test_mk_sparse(self):
# https://en.wikipedia.org/wiki/Sparse_matrix#Dictionary_of_keys_.28DOK.29
raw = {'A': {'x', 'y', 'z'}, 'B': {'w', 'y'}}
expected = {('A', 'x'): 1, ('B', 'y'): 1, ('A', 'z'): 1, ('A', 'y'): 1, ('B', 'w'): 1}
tested = mk_sparse(raw)
msg = '\nExpected:\n{}\nGot:\n{}'.format(expected, tested)
self.assertEqual(expected, tested, msg=msg)
def mk_sparse(dic):
'''
Returns a DOK sparse matrix ( (k,v):1 ) from a k:set_of_v dict
'''
keys = chain(*( [(samp,f) for f in feats] for samp, feats in dic.iteritems() ))
return {k:1 for k in keys}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment