The Social Network

social-network

Six Degrees of Separation


The Six degrees of separation is an idea that was originally set out by Frigyes Karinthy in 1929 and that can be applied to Social Networks such as Facebook.

It is based on the idea that all human beings in the world are six or fewer steps away from each other so that a chain of “a friend of a friend” statements can be made to connect any two people in a maximum of six steps.

Using a Graph:


In order to verify this concept, we are going to use a graph data structure where all the nodes of the graph will represent the members of a small social network that contains 100 members.

social-network-graph
The connections between the nodes will represent the friendship relationships between two members.

We will then ask the end-user to enter 2 names and use an algorithm to find out the shortest friendship chain between these two members (if it exists).

Using Graphs in Python


Most programming languages do provide direct support for graphs as a data type. Python for instance does not have a graph data structure. However, graphs can be built out of lists and dictionaries. For instance, here is the Python code to represent the connections from the above graph:

This graph is a dictionary where the keys are the nodes of the graph. For each key, the corresponding value is a list containing the nodes that are connected by a direct arc from this node.

The full dictionary with all the members of our social network can be found in the Python trinket below.

Shortest Path Algorithm


Our shortest path algorithm will be based on a recursive function used to find all the friendship chains/paths that can been found between two members and identify which one is the shortest path (The path that has the smallest number of nodes).

To make this algorithm more effective we also have a stopping condition to stop exploring a path that would be longer than the shortest path found so far.

Python Code


Check the code below used the find_shortest_path() algorithm to find the shortest path between two members. It is then used to calculate the degree of separation (based on the lenght of the chain).

Share Button
Tagged with: , , ,