Ask Your Question

problem with list: how to count different elements?

asked 2014-07-09 09:47:39 -0500

mresimulator gravatar image

updated 2014-07-09 09:48:29 -0500

Hello experts!

Im working with graphs.

My code is:

import numpy as np
import networkx as nx

M = np.zeros([6,6])




Doing that, A is a list with all the nodes connected with the node 2, ie: A=[0, 1, 2, 3, 2]

1) Why the element '2' is repeated? 2) If, instead, we use A=nx.node_connected_component(G,0), we get A=[0, 1, 2, 3]. In this case: why now the element '0' is not repeated? 3) If we have a list K=[1,2,3,4,1,1,1], and we do P=list(set(K)), we get P=[1,2,3,4] (doing that we can eliminate the repeated elements in the list). But if I do the same with the list A obtained in my code, I get A=[0, 1, 2, 3, 2]. Why this doest work?

Please help!

Thanks a lot

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2014-07-09 10:24:35 -0500

vdelecroix gravatar image

updated 2014-07-12 14:41:28 -0500


This is a problem with Sage integers fighting with numpy integers

sage: A[2] == A[4]
sage: type(A[2])
<type 'sage.rings.integer.Integer'>
sage: type(A[4])
<type 'numpy.int64'>

You can solve the issue working only with Sage integers as follows

sage: M = matrix(6)
sage: M[0,2]=M[2,0]=M[2,3]=1
sage: M[3,2]=M[2,1]=M[1,2]=1
sage: M[4,5]=M[5,4]=1
sage: G = Graph(M)
sage: A = G.connected_component_containing_vertex(2)
sage: A
[0, 1, 2, 3]

(using networx is fine as well)

There is already an old ticket related to that problem on the Sage trac server: #13386: comparison of Sage integer with Numpy integer

EDIT: if you want to solve it on your example, use

sage: nx.node_connected_component(G,
[0, 1, 2, 3]

If you use only numpy and networkx, there is no need to use Sage. Just use the standard Ipython you will have less troubles.


edit flag offensive delete link more


Thanks a lot Vincent. The problem is that in my full-code, 'M' is an numpy array with NxN element. How can I fix my problem keeping workin this this Numpy array? Thanks

mresimulator gravatar imagemresimulator ( 2014-07-10 17:02:56 -0500 )edit

I updated my answer accordingly. But I do not see the point of using numpy and networkx inside Sage.

vdelecroix gravatar imagevdelecroix ( 2014-07-12 14:42:02 -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

1 follower


Asked: 2014-07-09 09:47:39 -0500

Seen: 86 times

Last updated: Jul 12 '14