Search code examples
pythondata-structuresrecursioncyclic-reference

What is a cyclic data structure good for?


I was just reading through "Learning Python" by Mark Lutz and came across this code sample:


>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]

It was identified as a cyclic data structure.

So I was wondering, and here is my question:

What is a 'cyclic data structure' used for in real life programming?

There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L


>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'


Solution

  • Lots of things. Circular buffer, for example: you have some collection of data with a front and a back, but an arbitrary number of nodes, and the "next" item from the last should take you back to the first.

    Graph structures are often cyclic; acyclicity is a special case. Consider, for example, a graph containing all the cities and roads in a traveling salesman problem.


    Okay, here's a particular example for you. I set up a collection of towns here in Colorado:

    V=["Boulder", "Denver", "Colorado Springs", "Pueblo", "Limon"]
    

    I then set up pairs of cities where there is a road connecting them.

    E=[["Boulder", "Denver"],
       ["Denver", "Colorado Springs"],
       ["Colorado Springs", "Pueblo"],
       ["Denver", "Limon"],
       ["Colorado Springs", "Limon"]]
    

    This has a bunch of cycles. For example, you can drive from Colorado Springs, to Limon, to Denver, and back to Colorado Springs.

    If you create a data structure that contains all the cities in V and all the roads in E, that's a graph data structure. This graph would have cycles.