More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
◑ Python IDE Dashboard

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 not necessary provide direct support for graphs as a data type. Python for instance does not have a graph data structure. However it is possible to create a graph data structure in python using any of the following two methods:

  • Method 1: Adjacency Matrix: Using a 2D array (or list of lists in Pyhon)
  • Method 2: Us: Using a hash table (dictionary) of lists

Let’s investigate both approaches.

Method #1: Implementing a graph using an adjacency matrix

An adjacency matrix is a 2D array that has the same number of rows and columns: 1 row and 1 column per node of the graph.

Eshan Sonia Jackson Naomi Zheng Kamal Oliver May
Eshan ✔ ✔
Sonia ✔ ✔
Jackson ✔ ✔
Naomi ✔ ✔ ✔
Zheng ✔ ✔
Kamal ✔ ✔ ✔
Oliver ✔ ✔
May ✔ ✔

Here is how we could implement this adjacency matrix in Python:

members =    ["Eshan","Sonia","Jackson","Naomi","Zheng","Kamal","Oliver","May"]

#Adjacency Matrix: (2D array to store friendship data)
friendship = [[False , True  , False   , False , False , False , False  , True ], #Eshan
              [True  , False , True    , False , False , False , False  , False], #Sonia
              [False , True  , False   , True  , False , False , False  , False], #Jackson
              [False , False , True    , False , False , True  , False  , True ], #Naomi
              [False , False , False   , False , False , False , False  , False], #Zheng
              [False , False , False   , True  , True  , False , True   , False], #Kamal
              [False , False , False   , False , True  , True  , False  , False], #Oliver
              [True  , False , False   , True  , False , False , False  , False]  #May
             ]

Now that we have saved this data into our code, we can create a small program to query this data. For instance, let’s write a program that asks the user to enter the names of two members of our social network and output whether these two members are friends or not.

Note that using an adjacency matrix is not recommended for very large graphs where you have two many nodes. This is because, for a graph of n nodes the resulting 2D array would contain n2 values. This is can quickly be too demanding in terms of memory requirements (O(n2) Big O Notation)

Method #2: Implementing a graph using a hash table

An alternative approach to implement a graph is to use a hash table where each node of the graph is a key, and the value for each key is the list of adjacent nodes of this node. For instance, here is the Python code to represent the connections from our friendship graph:

members = {'Naomi': ['Jackson', 'May', 'Kamal'],
'May': ['Eshan', 'Naomi'],
'Jackson': ['Naomi', 'Sonia'],
'Kamal': ['Oliver', 'Naomi', 'Zheng'],
'Eshan': ['Sonia','May'],
'Sonia': ['Eshan','Jackson'],
'Zheng': ['Kamal','Oliver'],
'Oliver': ['Zheng','Kamal']
}

This graph is a hash table (a.k.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.

Let’s see how we can use this graph to complete our friendship checker program:

Shortest Path Algorithm


Two find out the degrees of separations between two members of our social network, we will need to identify the shortest path between these two members (nodes). We will use a shortest path algorithm to do so, using a graph based on a hash table (method #2).

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.

def find_shortest_path(graph, start, end, shortestLength=-1, path=[]):
  path = path + [start]
  if start == end:
    return path
  if not start in graph:
    return None
  shortest = None
  for node in graph[start]:
    if node not in path:
      if shortestLength==-1 or len(path)<(shortestLength-1):
        newpath = find_shortest_path(graph, node, end, shortestLength, path)
        if newpath:
          if not shortest or len(newpath) < len(shortest):
            shortest = newpath
            shortestLength = len(newpath)  
  return shortest

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 length of the chain).


unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , , ,

Estimating Pi using the Monte Carlo Method

pi-3-14159One method to estimate the value of Ď€ (3.141592…) is by using a Monte Carlo method. This methods consists of drawing on a canvas a square with an inner circle. We then generate a large number of random points within the square and count how many fall in the enclosed circle.
estimating-pi-monte-carlo-method

The area of the circle is πr2,
The area of the square is width2 = (2r)2 = 4r2.

If we divide the area of the circle, by the area of the square we get π/4.

The same ratio can be used between the number of points within the square and the number of points within the circle.

Hence we can use the following formula to estimate Pi:

Ď€ ≈ 4 x (number of points in the circle / total number of points)

Python Turtle Simulation


Run the code below to estimate Pi using the Monte Carlo Method.

Note: You may reach a better estimate of Pi by:

  • Increasing the radius of the circle. (e.g. radius = 1000) as it will give you a circle with a “higher resolution”.
  • Increasing the number of dots. (e.g. total = 5000)

Extension


You can find out more about the Monte Carlo method and its applications.
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,

Space Invaders – 3D Pixel Art

space-invaders-pixel-artIn this blog post we will use Glowscript to create a 3D animation of a space invader.

2D Graphics used in retro arcade games consist of pixels. A 2D graphic can be described as a grid of pixels of different colours.
space-invaders-pixels

In programming we can use a 2D array data structure to represent a graphic. In Python, 2D arrays are implemented using a list of lists.

In our code (see below) we have declared a 2D array called pixels to store the value of each pixel used to represent one of the space invaders.

pixels   =   [[0,0,1,0,0,0,0,0,1,0,0]]
pixels.append([0,0,0,1,0,0,0,1,0,0,0])
pixels.append([0,0,1,1,1,1,1,1,1,0,0])
pixels.append([0,1,1,0,1,1,1,0,1,1,0])
pixels.append([1,1,1,1,1,1,1,1,1,1,1])
pixels.append([1,0,1,1,1,1,1,1,1,0,1])
pixels.append([1,0,1,0,0,0,0,0,1,0,1])
pixels.append([0,0,0,1,1,0,1,1,0,0,0])

Using a 2 nested loops we then looped through each row and each column of this array to retrieve the value of each pixel in order to create the cubes needed to create a 3D model of a space invader.

We then create a compound object to join these cubes together in a single object. Finally using an infinite while loop we animate/rotate our invader around itself.

Here is our 3D animation: (Use Google Chrome to preview this animation)


Right Click on the animation to change the view point (rotate camera angle).

Find out more…


To learn more about all the instructions you can use in GlowScript/VPython, use this on-line documentation.

Your task:


space-invaders
Create and animate all the different Space Invaders.

From 2D to 3D: Crossy Road Chicken


This technique of creating 2D graphics can also be used for 3D graphics. In this case a 3D array is used to store the pixels alongside 3 dimensions: x, y and z.

Let’s look at the code below used to create a 3D model of the chicken from the Crossy Road game:
crossy-road-chicken

Check in the code below to see how a list of lists of lists is used in Python to create a 3D array.

Also look at how, using 3 nested loops we can iterate through each “pixel” of the 3D array.

We have also used a 1D array called palette to store all the colours to be used in our 3D model.

Can you think of other games that might use 3D arrays?
mine-craft-block

Tagged with: , , , , ,

London Underground – Journey Planner

london-underground-signThe aim of this Python challenge is to investigate how graphs can be used in Computer Science and investigate the key algorithms used when manipulating graphs in Python such as an algorithm to find the shortest path between two nodes of a graph.

For this challenge we will focus on a graph used to represent the London Underground Map (Zone 1).
tubemap

Access London Tube Map

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 a graph to represent some of the connections between a selection of London tube stations:

tubemap = {"Aldgate" : ["Liverpool Street","Tower Hill"],
"Aldgate East" : ["Tower Hill","Liverpool Street"],
"Angel" : ["King's Cross St. Pancras","Old Street"],
"Baker Street" : ["Marylebone","Regent's Park","Edgware Road (C)","Great Portland Street","Bond Street"],
"Bank" : ["Liverpool Street","St. Paul's","London Bridge","Moorgate","Waterloo"],
"Barbican" : ["Farringdon","Moorgate"]
#...
}

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 stations for London Underground can be found in the Python trinkets below.

Find Path Algorithm


Our first algorithm is used to determine if there is a path between two nodes of a graph, and if so it returns one path that can be used to connect both nodes. A path is a list of nodes which are connected to each others.

This algorithm uses a backtracking approach to explore different paths. It does stop as soon as a path has been found. Note that the path that will be found first may not be the shortest path though.

def find_path(graph, start, end, path=[]):
  path = path + [start]
  if start == end:
    return path
  if not start in graph:
    return None
  for node in graph[start]:
    if node not in path:
      newpath = find_path(graph, node, end, path)
      if newpath: return newpath
  return None

Find All Paths Algorithm


This second algorithm is very similar to the find_path() algorithm. The difference is that this time the backtracking algorithm will explore and return all the possible paths between the two nodes as a list of paths. (List of lists).

def find_all_paths(graph, start, end, path=[]):
  path = path + [start]
  if start == end:
    return [path]
  if not start in graph:
    return []
  paths = []
  for node in graph[start]:
    if node not in path:
      newpaths = find_all_paths(graph, node, end, path)
      for newpath in newpaths:
        paths.append(newpath)
  return paths

Find Shortest Path Algorithm


Our final algorithm is probably the most useful algorithm as it will identify amongst all the paths that have been found, 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.

def find_shortest_path(graph, start, end, shortestLength=-1, path=[]):
  path = path + [start]
  if start == end:
    return path
  if not start in graph:
    return None
  shortest = None
  for node in graph[start]:
    if node not in path:
      if shortestLength==-1 or len(path)<(shortestLength-1):
        newpath = find_shortest_path(graph, node, end, shortestLength, path)
        if newpath:
          if not shortest or len(newpath) < len(shortest):
            shortest = newpath
            shortestLength = len(newpath)  
  return shortest

Python Code


We will use the find_shortest_path() algorithm to find the shortest path between two tube stations.

Zone 1 OnlyFull Map (Zone 1 to 10)

With a more complex graph, this algorithm will take longer to find the shortest path.

Extension


A backtracking algorithm can sometimes take a very long time to explore all possible paths. This is due to the complexity of the graph (e.g. tube map) which contains many nodes and connections between nodes, hence the high number of potential routes to explore using a backtracking algorithm.

More advanced algorithms can be implemented to overcome this issue. You may want to explore the following algorithms:

Tagged with: , ,

Insertion Sort Algorithm

Insertion-sort-1-9The Insertion sort algorithm is one of the key sorting algorithms used in Computer Science.

To start with, the algorithm considers the first value of a list as a sorted sub-list (of one value to start with). This iterative algorithm then checks each value in the remaining list of values one by one. It inserts the value into the sorted sub-list of the data set in the correct position, moving higher ranked elements up as necessary.

This algorithm is an O(n2) algorithm which is relatively efficient for small lists and mostly sorted lists, and is often used as part of more sophisticated algorithms.

Python Implementation of an Insertion Sort algorithm


The Python code belows let you visualise how a Insertion sort algorithm with a small set of values (from 1 to 9). The list of values is shuffled every time you run this code.

Tagged with: , ,

Bubble Sort Algorithm

Bubble-sort-1-9The Bubble sort algorithm is one of the key sorting algorithms used in Computer Science. It is a fairly simple algorithm to implement and is particularly useful when you need to find the top x values of a list.

The algorithm starts at the beginning of the data set. It compares the first two value, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent values to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass.

This algorithm’s average and worst-case performance is O(n2), so it is rarely used to sort large, un-ordered data sets. Bubble sort can be used to sort a small number of items and is a lot more effective on data sets where the values are already nearly sorted.

Python Implementation of a Bubble Sort algorithm


The Python code belows let you visualise how a Bubble sort algorithm with a small set of values (from 1 to 9). The list of values is shuffled every time you run this code.

Tagged with: , ,

Backtracking Maze – Path Finder

backtracking-maze-algorithmThe purpose of this Python challenge is to demonstrate the use of a backtracking algorithm to find the exit path of Maze.

Backtracking Algorithm


A backtracking algorithm is a recursive algorithm that attempts to solve a given problem by testing all possible paths towards a solution until a solution is found. Each time a path is tested, if a solution is not found, the algorithm backtracks to test another possible path and so on till a solution is found or all paths have been tested.

The typical scenario where a backtracking algorithm is when you try to find your way out in a maze. Every time you reach a dead-end, you backtrack to try another path until you find the exit or all path have been explored.

Backtracking algorithms can be used for other types of problems such as solving a Magic Square Puzzle or a Sudoku grid.

Backtracking algorithms rely on the use of a recursive function. A recursive function is a function that calls itself until a condition is met.

Python Code

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,

Backtracking Algorithm – Sudoku Solver

The purpose of this Python challenge is to demonstrate the use of a backtracking algorithm to solve a Sudoku puzzle.

Did You Know?


The objective of a Sudoku puzzle is to fill a 9Ă—9 grid with digits so that each column, each row, and each of the nine 3Ă—3 subgrids that compose the grid (also called “boxes”) contains all of the digits from 1 to 9. A Sudoku puzzle is a partially completed grid, which for a well-posed puzzle has a single solution.

sudoku-grid

Backtracking Algorithm


A backtracking algorithm is a recursive algorithm that attempts to solve a given problem by testing all possible paths towards a solution until a solution is found. Each time a path is tested, if a solution is not found, the algorithm backtracks to test another possible path and so on till a solution is found or all paths have been tested.

The typical scenario where a backtracking algorithm is when you try to find your way out in a maze. Every time you reach a dead-end, you backtrack to try another path untill you find the exit or all path have been explored.

Backtracking algorithms can be used for other types of problems such as solving a Magic Square Puzzle or a Sudoku grid.

Backtracking algorithms rely on the use of a recursive function. A recursive function is a function that calls itself until a condition is met.

Note that there are other approaches that could be used to solve a Sudoku puzzle. The Backtracking approach may not always be the most effective but is used in this challenge to demonstrate how a backtracking algorithm behaves and how it can be implemented using Python.

Python Code


Extra Challenge:


An extra challenge would be to design an algorithm used to create a Sudoku Grid. The generated Sudoku grid should have enough clues (numbers in cells) to be solvable resulting in a unique solution.
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,

Backtracking Algorithm – Magic Square Solver

magic-squareThe purpose of this Python challenge is to demonstrate the use of a backtracking algorithm to solve a Magic Square puzzle.

Did You Know?


A 3×3 magic square is an arrangement of the numbers from 1 to 9 in a 3 by 3 grid, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal is the same.

magic-square-3x3

Backtracking Algorithm


A backtracking algorithm is a recursive algorithm that attempts to solve a given problem by testing all possible paths towards a solution until a solution is found. Each time a path is tested, if a solution is not found, the algorithm backtracks to test another possible path and so on till a solution is found or all paths have been tested.

The typical scenario where a backtracking algorithm is when you try to find your way out in a maze. Every time you reach a dead-end, you backtrack to try another path until you find the exit or all paths have been explored.

Backtracking algorithms can be used for other types of problems such as solving a Magic Square Puzzle or a Sudoku grid.

Backtracking algorithms rely on the use of a recursive function. A recursive function is a function that calls itself until a condition is met.

Note that there are other approaches that could be used to solve the magic square puzzle. The Backtracking approach may not be the most effective but is used in this challenge to demonstrate how a backtracking algorithm behaves and how it can be implemented using Python.

Python Code


Extension Task


Adapt this challenge to implement a backtracking algorithm used to solve a Sudoku grid!
sudoku-grid
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,

Food Chain Game Using Python

food-chain-frog

Learning Objectives?


In this set of Python challenges we will investigate the use of two data structures used in programming to represent data:

  • We will use an array/list to represent a food chain.
  • We will use a graph to represent a food web.

Did you know?


A food chain shows the different organisms that live in a habitat, and what eats what.

A predator is an animal that eats other animals, and the prey is the animal that gets eaten by the predator.

Here is an example of food chain:

Grass > grasshopper > frog > snake > eagle

In the food chain above:

  • the frog is a predator and the grasshopper is its prey.
  • the snake is a predator and the frog is its prey.

Python Challenge

For this challenge you will write a Python program that stores the organisms a food chain using a list.

food-chain

You program will randomly pick two organisms from the food chain. One for the player, one for the computer.

The program will find out the positions of these organisms in the given food chain. (This is known as the trophic level of an organism which is the position it holds in a food chain).

The program will compare both positions, the player with the highest position in the food chain will win the game.

We have started the code for you. Complete this code to:

  • Randomly select the “computer organism” from the list.
  • Make sure that both selected organisms are different.
  • Compare the positions of both organisms to decide who, between the computer and the player, wins the round.

Food Web


When all the food chains in a habitat are joined up together they form a food web. Here is an example of a food web:

food-web

Although it looks complex, it is just several food chains joined together. Here are some of the food chains in this food web:

grass > insect > vole > hawk

grass > insect > frog > fox

grass > insect > vole > fox

To represent a food web we will use a different data structure called a graph.

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 a graph to represent the above food web:

foodWeb = {'insect': ['grass'],
           'rabbit': ['grass'],
           'slug': ['grass'],
           'thrush': ['slug','insect'],
           'vole': ['insect'],
           'frog': ['insect'],
           'hawk': ['frog','vole','thrush'],
           'fox': ['rabbit','frog','vole']}

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. Note that this is a directed graph as each link/arc has a direction.

Python Code

Compete the code below to:

  • Find out if the computer organism and the player organism are linked (Direct link or indirect link).
  • If a link/path is detected, decide who, between the computer and the player, wins the game.

Tip: Use the find_path() algorithm described on https://www.python.org/doc/essays/graphs/


unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,
Privacy Overview

This website will store some information about your preferences on your own computer inside a tiny file called a cookie. A cookie is a small piece of data that a website asks your browser to store on your computer or mobile device. The cookie allows the website to remember your actions or preferences over time.

You can delete all cookies that are already on your computer, and you can set most browsers to prevent them from being placed. However, if you do this, you may have to manually adjust some preferences every time you visit a site, and some services and functionalities may not work.

Most browsers support cookies, but you can set your browser to decline them and can delete them whenever you like. You can find instructions here for how you can do that on various browsers.

This website uses cookies to:

  1. Identify you as a returning user and to count your visits in traffic statistics analysis
  2. Remember your custom display preferences (such as light/dark theme option)
  3. Provide other usability features, including tracking whether you have already given your consent to cookies

Enabling cookies is not strictly necessary for the website to work but it will provide you with a better browsing experience.

The cookie-related information is not used to identify you personally and is not used for any purpose other than those described here.

There may also be other types of cookies created after you have visited this website. This site uses Google Analytics, a popular web analytics service that uses cookies to help to analyse how users use the site. The information generated by the cookie about your use of this website (including your IP address) will be transmitted to and stored by Google on servers in the United States. Google will use this information for the purpose of evaluating your use of other website, compiling reports on website activity, and providing other services relating to website activity and internet usage. Google may also transfer this information to third parties where required to do so by law, or where such third parties process the information on Google’s behalf. Google undertakes not to associate your IP address with any other data held by Google.