# multiplicity of elements in a list

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 close merge delete

I slightly edited your question to make it clearer.

( 2013-05-01 08:55:53 +0200 )edit

Sort by ยป oldest newest most voted

Hi,

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)
4
sage: l.count("four")
2


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


Vincent

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.

( 2013-05-01 11:54:34 +0200 )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().

( 2013-05-01 16:35:12 +0200 )edit

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

( 2013-05-01 16:53:18 +0200 )edit