1

So I got this really cool book from university library today, Python Algorithms by Magnus Lie Hetland and in the Chapter second of the book he creates the adjacency list as follows, which was kind of cool:

a,b,c,d,e,f,g,h = range(8)
N = [{b,c,d,e,f},{c,e},{d},{e},{f},{c,g,h},{f,h},{f,g}]

And when I do:

N[a] I get the first element of N, and it's kind of surprising me how did it got mapped in such a manner?

I found this question but it's different than what I am asking still let me know if it's a duplicate.

Adjacency List and Adjacency Matrix in Python

Thanks, Prerit

Community
  • 1
  • 1
Slayer
  • 832
  • 1
  • 6
  • 21

1 Answers1

2

It's just Python.

a,b,c,d,e,f,g,h = range(8)

is tuple assignment. It assigns 0 to a, 1 to b, etc.

N = [{b,c,d,e,f},{c,e},{d},{e},{f},{c,g,h},{f,h},{f,g}]

creates an array named N where the 0'th element is the set {b,c,d,e,f}, etc.

So when you say N[a], you're also saying N[0], and that's the set you're seeing.

It's a cool trick for building a constant graph by hard-coding in Python, but if you need to build the graph dynamically based on input or output from another algorithm, then you'll want a different representation.

Gene
  • 46,253
  • 4
  • 58
  • 96
  • I had my suspicions but I thought it just maps whatever I created above, but what if the number of elements inside it exceeds 26 characters of alphabet, so does it start indexing them by aa,ab,ac...etc? – Slayer Feb 14 '17 at 02:10
  • I know about other representation I am just going through the book. You never know what you might learn from an introductory book (kind of). :) – Slayer Feb 14 '17 at 02:12