First time here? Check out the FAQ!

Ask Your Question
0

problem with list: how to count different elements?

asked 10 years ago

mresimulator gravatar image

updated 10 years ago

Hello experts!

Im working with graphs.

My code is:

import numpy as np
import networkx as nx

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

M[0,2]=1
M[2,0]=1
M[2,3]=1
M[3,2]=1
M[2,1]=1
M[1,2]=1
M[4,5]=1
M[5,4]=1

G=nx.Graph(M)

A=nx.node_connected_component(G,2)

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

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 10 years ago

vdelecroix gravatar image

updated 10 years ago

Hi,

This is a problem with Sage integers fighting with numpy integers

sage: A[2] == A[4]
False
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, np.int(2))
[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.

Vincent

Preview: (hide)
link

Comments

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

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

vdelecroix gravatar imagevdelecroix ( 10 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

1 follower

Stats

Asked: 10 years ago

Seen: 682 times

Last updated: Jul 12 '14