More results...

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

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: ,

Lighthouse Animation Challenge

lighthouseThe purpose of this challenge is to use a Python program to demonstrate how frame-based animations can be implemented.

For this challenge we are using the Processing.py library.

The code below will run the setup() procedure once, when the program starts. Then the animateLighthouse() procedure will be called 20 times per second (based on the frame rate), indefinitely.

This code makes use of two transformations:

  • A translation: 2D translations are often used to re-position or animate objects on screen (gliding effect)
  • A rotation: in this case, a rotation is applied to animate the light beam. The angle of rotation increments by 0.5 degrees between each frame.

lighthouse-translation-rotation

Python Code


Your Challenge


Complete this code to animate the boat:

  • The boat should translate/glide horizontally from left to right.
  • Once the boat fully disappears to the right of the screen, it should reappear to the left.

lighthouse-translation

unlock-access

Solution...

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

Python Turtle – WordArt Challenge

In this challenge we will use Python Turtle to draw text on screen and customise the appearance of our text.

To do so we have created our own font as a Python dictionary. Each letter of the alphabet is represented as a set of (x,y) coordinates as follows:
character-A-dot-to-dot
We will then use these coordinates to trace a line using Python Turtle using a “dot-to-dot” approach.

WordArt #1: Dot-To-Dot Text


WordArt #2: Oblique Text


WordArt #3: Circular Text


Your Challenge


Customise the code above to create your own WordArt effects such as:

  • Growing Text: Write text where each letter is bigger than the previous one.
  • Backwards Text: Write text where the text is written backwards.
  • Vertical Text: Write text where the text is written vertically.
  • Wrapped Text: Write text where long text is written across multiple lines.
  • Reflective Text: Write text with its own reflection underneath.
Tagged with: ,

Confetti Artwork Challenges

confetti-blueFor these challenges we will produce on screen artwork by randomly positioning confetti on different shapes of canvas. Our code will use Python Turtle to draw the canvas and the confetti.

Square Canvas


Check how the code provided below randomly positions each confetti within the boundaries of a square canvas:

Circular Canvas


Check how the code provided below randomly positions each confetti within the boundaries of a circular canvas:

Challenge #1: Ring Canvas


Adapt the code provided below to randomly position each confetti within the boundaries of a ring/doughnut shape:

Challenge #2: Diamond Canvas


Adapt the code provided below to randomly position each confetti within the boundaries of a diamond shape:

Challenge #3: Triangular Canvas


Adapt the code provided below to randomly position each confetti within the boundaries of an equilateral triangle:

unlock-access

Solution...

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

Confetti Challenge

confettiIn this Python challenge we will write a script to randomly draw confetti on a canvas while ensuring that none of the confetti overlap with each other!

Problem Decomposition


In this challenge we will need to solve the following problems:

  1. How to draw confetti on screen?
  2. How to randomly position a confetti on screen?
  3. How detect if a confetti is overlapping with another confetti?
  4. How to detect an overlap with any of the confetti already positioned on screen?
  5. How to randomise the colour of a confetti?
Problem Solution
How to draw confetti on screen? Using the Python Turtle library we can easily draw circles on the screen.
How to randomly position a confetti on screen? By generating two random numbers representing the x and y coordinates of the confetti. These coordinates will be used in Python Turtle to draw a circle on screen at the right (x,y) location.
How detect if a confetti is overlapping with another confetti? Using Pythagoras formula we can calculate the distance between two confetti.
If this distance is lower than 2*radius of a confetti, then the two confetti are overlapping.
confetti-pythagoraconfetti-overlap-detection
How to detect an overlap with any of the confetti already positioned on screen? When a confetti is placed on screen its coordinates will be appended to a list. Each time a new set of coordinates is generated we will iterate through the list of confetti one at a time (using a for loop) to check if an overlap is detected. If so, we will generate a new set of random (x,y) coordinates and repeat this process until no overlap is detected. We will then append this final set of coordinates to the list of confetti.
How to randomise the colour of a confetti? We want all confetti to have a purple shade. To do so we will randomise their colour code using the RGB codes with a random Red value (between 50 and 255), a Green value set to 0, a random Blue value (between 50 and 255).

Implementation


Check the Python code for this challenge:

Your Python Challenge


Generate confetti of random sizes (random radius between 10 and 30 pixels).
Adapt your algorithm to make sure these confetti still don’t overlap.
confetti-overlap-radius
unlock-access

Solution...

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

Binary Shift using Python

Did You Know?

Everything that is stored on a computer is stored as binary code. Binary code is made of bits (0 or 1). We often use Bytes to store data. A Byte is made of eight bits and can be used to store any whole number between 0 to 255. Check it yourself, click on the binary digits to create your own binary number:

1286432168421
11111111

128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255


Binary Left Shift


A binary left shift is used to multiply a binary number by two. It consists of shifting all the binary digits to the left by 1 digit and adding an extra digit at the end with a value of 0.
binary-left-shift

Binary Right Shift


A binary right shift is used to divide a binary number by two. It consists of shifting all the binary digits to the right by 1 digit and adding an extra digit at the beginning (to the left) with a value of 0.
binary-right-shift

Multiple-digit Left and Right Shifts


A two-digit left shift consists of two consecutive left shifts on a binary number and is the equivalent of timing this number by 22=4.

A three-digit left shift consists of three consecutive left shifts on a binary number and is the equivalent of timing this number by 23=8. (and so on…)

A two-digit right shift consists of two consecutive right shifts on a binary number and is the equivalent of dividing this number by 22=4.

A three-digit right shift consists of three consecutive right shifts on a binary number and is the equivalent of dividing this number by 23=8. (and so on…)

Python Challenge


The purpose of this challenge is to write a Python script to perform a binary shift. Our Python program will:

  • Ask the user to enter an 8-bit binary number,
  • Ask the user whether they would like to perform a left shift or a right shift,
  • Ask the user whether the number of digits they want to shift,
  • Output the resulting 8-bit binary number.

Test Plan

Test # Input Values Expected Output Actual Output
Binary Number Left/Right Shift? Number of digits
#1 00111100 Left 1 01111000
#2 00111100 Right 1 00011110
#3 00111100 Left 2 111110000
#4 00111100 Right 2 00001111
#5 00001111 Left 3 01111000
#6 00001111 Right 3 0000001

Python Code



unlock-access

Solution...

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

Code Breaker Challenges – Series 3

padlock-closed

Crack the Codes! (open full screen)


In this set of challenges, you will analyse some pseudocode to try to get the pass codes required to move on to the next levels. Levels will get more and more complex as your progress through these challenges. Will you be able to crack all the codes?

Tagged with:

Code Breaker Challenges – Series 2

padlock-closed

Crack the Codes! (open full screen)


In this set of challenges, you will analyse some pseudocode to try to get the pass codes required to move on to the next levels. Levels will get more and more complex as your progress through these challenges. Will you be able to crack all the codes?

Tagged with: