1

if I have a directed graph whose vertices are denoted by {1,2,3,...} and the connections between them are like this:(meaning there is a directed edge from b to a represented as a<-b)

List1: 1<-2<-3<-4<-5<-6
List2: 2<-4<-7<-6
List3: 1<-8<-7
List4: 1<-9<-2

The degree of vertex 4 is 2 (since it has a edge to 3 and 2), degree of 6 is 2 and so on. How can I compute this and store this in a dictionary in python as shown below:

dict = {}
dict{4:'2', 6:'2'} 

like this. Thanks in advance.

3
  • What does your actual input look like? Commented Apr 18, 2016 at 16:59
  • My input looks like this : words[] = ['4777', '2516', '4637', '1221', '38803', '56203']. Where each element is connected by a directed edge to its previous element. Commented Apr 18, 2016 at 17:00
  • what's the degree of 7 in that input? Given 4777 and 4637, is it 4 or 2? Commented Apr 18, 2016 at 17:15

1 Answer 1

1

Try the following,

l1 = [1, 2, 3, 4, 5, 6]
l2 = [2, 4, 7, 6]
l3 = [1,8,7]
l4 = [1, 9, 2]

from collections import defaultdict
d = defaultdict(list)

for l in [l1, l2, l3, l4]:
    for i,n in enumerate(l):
         if i:
             d[n].append(l[i-1])
In [144]: d
Out[144]:
defaultdict(list,
        {2: [1, 9],
         3: [2],
         4: [3, 2],
         5: [4],
         6: [5, 7],
         7: [4, 8],
         8: [1],
         9: [1]})

You can do all the operations on defaultdict that you can on dict. So if you want to count the degrees,

degree = {k: len(v) for k,v in d.items()}
In [146]: degree
Out[146]: {2: 2, 3: 1, 4: 2, 5: 1, 6: 2, 7: 2, 8: 1, 9: 1}
Sign up to request clarification or add additional context in comments.

3 Comments

hey what are 144 and 146 here? I am sorry I am new to this concept
@Nikhil They are part of the terminal prompt.Not part of code.
@Nikhil You will have >>> Type >>> d or >>> degrees

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.