Ask Your Question
1

multiplicity of elements in a list

asked 11 years ago

REKHA BISWAL gravatar image

updated 11 years ago

vdelecroix gravatar image

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).

Preview: (hide)

Comments

I slightly edited your question to make it clearer.

vdelecroix gravatar imagevdelecroix ( 11 years ago )

1 Answer

Sort by » oldest newest most voted
2

answered 11 years ago

vdelecroix gravatar image

updated 11 years ago

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

Preview: (hide)
link

Comments

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 ( 11 years ago )

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 ( 11 years ago )

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

fidbc gravatar imagefidbc ( 11 years ago )

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 11 years ago

Seen: 3,073 times

Last updated: May 01 '13