Ask Your Question

multiplicity of elements in a list

asked 2013-05-01 01:08:57 -0500

REKHA BISWAL gravatar image

updated 2013-05-01 01:55:15 -0500

if one has a list of matrices how do we build a dictionary whose keys are the distinct matrices in the list and values are the number of times that matrix appears in the list (or the multiplicity of that matrix in the list).

edit retag flag offensive close merge delete


I slightly edited your question to make it clearer.

vdelecroix gravatar imagevdelecroix ( 2013-05-01 01:55:53 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2013-05-01 01:25:54 -0500

updated 2013-05-01 01:34:31 -0500


Here is a simple solution. Given a list that contains several elements, you may use the method .count() to get the multiplicity

sage: l = [1, 3, "four", 1, "four", 1, 3, 1, 3]
sage: l.count(1)
sage: l.count("four")

Now a more involved solution is to build a dictionnary. It is possible to do it using count() but it is not very elegant. Another way is to do a for loop:

sage: d = {}
sage: for i in l:
....:     if i not in d:
....:         d[i] = 0
....:     d[i] += 1
sage: print d
{'four': 2, 1: 4, 3: 3}

If you have a list of matrices, you need to be careful as a matrix is not necessarily immutable (which implies that it can not be used as a key of a dictionnary).

sage: d = {}
sage: m = identity_matrix(4)
sage: d[m] = 4
Traceback (most recent call last)
TypeError: mutable matrices are unhashable

In order to be able to use your matrices in a dictionnary, you need to set them immutable

sage: M = MatrixSpace(ZZ, 2)
sage: l = [M.random_element() for i in xrange(500)]  # 500 random matrices
sage: for m in l: m.set_immutable()                  # set them immutable
sage: d = {}
sage: for i in l:
....:     if i not in d:
....:         d[i] = 0
....:     d[i] += 1
sage: for m,mult in d.iteritems(): print m.list(), mult    
[5, -1, 2, -1] 1
[-1, 1, 0, 0] 1
[-6, 0, 2, 2] 1
[2, -3, 0, 1] 1


edit flag offensive delete link more


i want the keys in the dictionary of the output to be in matrix form but in your code keys are not in matrix form instead it puts all the entries of matrix in one row.

REKHA BISWAL gravatar imageREKHA BISWAL ( 2013-05-01 04:54:34 -0500 )edit

In my code, the entries of the dictionnary **are** in matrix form. I just decided to **print** them in row form in order to have the pair key/value on one line. Look at the code, it is written m.list().

vdelecroix gravatar imagevdelecroix ( 2013-05-01 09:35:12 -0500 )edit

Vincent is right, I missed the `m.list()` command. I'll delete my comment, as it is misleading. Thanks Vincent!

fidbc gravatar imagefidbc ( 2013-05-01 09:53:18 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2013-05-01 01:08:57 -0500

Seen: 456 times

Last updated: May 01 '13