More results...

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

Binary Permutations Challenge

binary-permutations

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. This is because with 8 bits you can generate 256 different permutations.

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


Python Challenge


The aim of this challenge is to write a procedure called listAllBinaryPermutations() that will take one parameter called numberOfBits and outputs all possible binary permutations depending on the number of bits.

For instance listAllBinaryPermutations(4) would output the following 16 binary permutations:

  • 0000
  • 0001
  • 0010
  • 0011
  • 0100
  • 0101
  • 0110
  • 0111
  • 1000
  • 1001
  • 1010
  • 1011
  • 1100
  • 1101
  • 1110
  • 1111

unlock-access

Solution...

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

Complementary Colours Algorithm

Complementary colours are pairs of colours which, when combined or mixed, cancel each other out by producing a grayscale colour like white or black. When placed next to each other, they create the strongest contrast for those two colours. Complementary colours may also be called “opposite colours.”.

To find out pairs of complementary colours we can use a colour wheel. Colours which are at the opposite position on the colour wheel are complementary colours:
complementary-colours

Complementary Colours Formula


When representing colours using the RGB colour code, we can use the following formula to work out the complementary RGB colour code:
complementary-colour-formula

Complementary Colours Algorithm


Our aim is to write a Python program, based on the INPUT, PROCESS and OUTPUT model in order to:

  1. INPUT: Ask the user to enter an RGB colour code
  2. PROCESS: Apply the complementary colour code formula to work out the RGB code of the complementary colour
  3. OUPUT: Display the complementary colour code on screen

Our code will be based on the following flowchart:
complementary-colours-flowchart

Casting


To complete this challenge, you will need to understand the importance of casting values from string to integer data types using the int() function and from integer to string using the str() function.

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:

My Weekly Timetable

A school timetable is displayed as a 2D table consisting of 5 rows (for each day of the week) and 5 columns (number of lessons in a day).

Such a table can be stored in a computer program using a 2-dimensional array (2d Array). In python, this is done by creating a list of lists.

Each value of a 2D array can then be accessed by proving two indices: the row number and the column number as displayed on the picture below:
my-timetable-2d-array

Python Challenges


The following 3 tabs contain 3 different challenges, all based on accessing information from the 2D array called timetable.

What Lesson?Today's Lessons?How Many Lessons?
Write a program that:

  1. Asks the user to input a day of the week (e.g. Tuesday)
  2. Asks the user to input a period of the day (between 1 and 5) (e.g. 2)
  3. Retrieves and outputs the lesson on that day and period (e.g. Spanish)
Write a program that:

  1. Asks the user to input a day of the week (e.g. Tuesday)
  2. Displays all five lessons for that day
Write a program that:

  1. Asks the user to input a subject (e.g. Maths)
  2. Counts and outputs the number of lessons for that subject throughout the week. (e.g. “You have 3 Maths lesson this week.”)

Python Code


Use the following code to complete all three challenges mentioned above:

Help?


The following lines of code will help you solve each of the three challenges.
What Lesson?Today's Lessons?How Many Lessons?
#INPUT
day = input("Day of the week?").title()
period = int(input("Lesson number (1 to 5):"))
while period<1 or period>5:
  period = int(input("Lesson number (1 to 5):"))

#PROCESS
lesson=""
if day=="Monday":
  lesson = timetable[0][period-1]
elif day=="Tuesday":
  lesson = timetable[1][period-1]
elif day=="Wednesday":
  lesson = timetable[2][period-1]
elif day=="Thursday":
  lesson = timetable[3][period-1]
elif day=="Friday":
  lesson = timetable[4][period-1]
else:
  print("Not a valid week day!")
  
#OUTPUT
if lesson!="":
  print("On " + day + ", lesson " + str(period) + " you have " + lesson + ".")

#INPUT
day = input("Day of the week?").title()

#PROCESS
lessons=[]
if day=="Monday":
  lessons = timetable[0]
elif day=="Tuesday":
  lessons = timetable[1]
elif day=="Wednesday":
  lessons = timetable[2]
elif day=="Thursday":
  lessons = timetable[3]
elif day=="Friday":
  lessons = timetable[4]
else:
  print("Not a valid week day!")
  
#OUTPUT
print("Your lessons on this day:")
for lesson in lessons:
  print(lesson)
#INPUT
subject= input("Enter Subject:")

#PROCESS
count=0
for day in range(0,5):
  for period in range(0,5):
    if timetable[day][period] == subject:
      count+=1
      
#OUTPUT
if count>1:
  print("You have " + str(count) + " " + subject + " lessons per week.")  
else:
  print("You have " + str(count) + " " + subject + " lesson per week.") 

Extension Task


Create three different functions for each of the three challenges and add a menu structure to your code to let the user decide what information to retrieve from their timetable.
unlock-access

Solution...

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

Colour Difference Formula

color-wheel-12-colors

RGB Colour Codes

Did you know that every colour on the screen can be represented using an RGB code (Red, Green, Blue) code. This code consists of three numbers between 0 and 255, indicating how much red, green and blue are used to recreate the colour. For instance the RGB code for:

  • Red is (255,0,0)
  • Green is (0,255,0)
  • Blue is (0,0,255)
  • Yellow is (255,255,0)
  • Orange is (255,165,0)

Graphic designer and software programmer sometimes prefer to use another notation based on hexadecimal RGB code where each of the three decimal values are converted into a two-digit hexadecimal code, resulting in a 6-digit (3×2) hexadecimal code. For instance:

  • Red is #FF000
  • Green is #00FF00
  • Blue is #0000FF
  • Yellow is #FFFF00
  • Orange is #FFA500

Check the following RGB Color picker to see how RGB codes work:

Using the RGB colour code we can represent 2563 = 16,777,216 colours.

Colour Wheel


A colour wheel is used to represent some of the most distinct colours. For instance the picture above represents a colour wheel that includes 12 colours:

RED (Hex: #FF0000 – RGB: 255, 0, 0)
ORANGE (Hex: #FF7F00 – RGB: 255, 127, 0)
YELLOW (Hex: #FFFF00 – RGB: 255, 255, 0)
CHARTREUSE GREEN (Hex: #7FFF00 – RGB: 127, 255, 0)
GREEN (Hex: #00FF00 – RGB: 0, 255, 0)
SPRING GREEN (Hex: #00FF7F – RGB: 0, 255, 127)
CYAN (Hex: #00FFFF – RGB: 0, 255, 255)
AZURE (Hex: #007FFF – RGB: 0, 127, 255)
BLUE (Hex: #0000FF – RGB: 0, 0, 255)
VIOLET (Hex: #7F00FF – RGB: 127, 0, 255)
MAGENTA (Hex: #FF00FF – RGB: 255, 0, 255)
ROSE (Hex: #FF007F – RGB: 255, 0, 127)

Colour Difference Formula


The colour difference formula is used to find out the “distance” between two colours:
color-difference-formula

We can use this formula to find out if two colours are very close (small difference).

Python Challenge


For this challenge, your task is to write a Python script that will:

  1. ask the user to input an RGB colour code,
  2. calculate the differences between this colour and each of the 12 colours of the above colour wheel,
  3. output the name of the closest colour from the colour wheel. (The colour with the smallest difference)

Test Plan


Once your code is done, complete the following tests to check that your code is working as it should:

Test # Input Values /Colour Code Expected Output Actual Output
#1 (222, 215, 21) Yellow
#2 (201, 45, 139) Rose
#3 (124, 180, 48) Charteuse Green
#4 (36, 180, 225) Azure
#5 (100, 50, 150) Violet
#6 (200, 100, 50) Orange
unlock-access

Solution...

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

Cell Phone Trilateration Algorithm

Mobile phone tracking is a process for identifying the location of a mobile phone, whether stationary or moving. Localisation may occur either via multilateration of radio signals between several cell towers and the phone, or simply via GPS.

Mobile positioning is used by telecommunications companies to approximate the location of a mobile phone and enables to offer location-based services and/or information to the mobile user.

Cell Phone Trilateration / Multilateration


Cell tower trilateration (sometimes referred as triangulation) is used to identify the location of the phone. A cell phone constantly emits roaming radio signals that may be picked up by three or more cell towers enabling the triangulation to work. Trilateration calculations estimate the coordinates of a mobile device using the coordinates (longitude,latitude) of nearby cell towers as well as the estimated distance of the device from the cell towers (e.g. either based on signal strength or by measuring the time delay that a signal takes to return back to the towers from the phone).

In this challenge we will investigate the math equations used in trilateration calculations. We will simplify the process by using a 2D model of the problem based on (x,y) coordinates (as an alternative to longitude/latitude coordinates).

trilateration-diagram

On the diagram above, each circle represents all the possible locations of a mobile phone at a given distance (radius) of a cell tower. The aim of a trilateration algorithm is to calculate the (x,y) coordinates of the intersection point of the three circles. Each circle is defined by the coordinates of its center e.g. (x1,y1) and its radius e.g. r1.

The following steps will help us calculate these (x,y) coordinates:

Step 1
The three equations for the three circles are as follows:
trilateration-formula-1

Step 2:
We can expand out the squares in each of these three equations:
trilateration-formula-2

Step 3:
Now let’s subtract the second equation from the first:
trilateration-formula-3a

Likewise, we can now subtract the third equation from the second:
trilateration-formula-3b

Step 4:
Let’s rewrite these two equations using A, B, C, D, E, F values. This would result in the following system of 2 equations:
trilateration-formula-4

Step 5:
The solution of this system is:
trilateration-formula-5

Python Implementation


Now that we understand the math needed in a trilateration calculation, let’s implement these equations in a Python algorithm using a function that will take 9 parameters (x1,y1r1,x2,y2r2,x3,y3r3) and return the (x,y) coordinates of the intersection point of the three circles.

Your task is to complete the code of the trackPhone() function that we have started for you:

GPS Positioning


Note that GPS satnav systems use a similar approach but need to be more accurate by:

  • Estimating the distance between a GPS satnav device and at least three GPS satellites. This is done by measuring the time delay that a signal takes to be sent from the satellite to the GPS satnav, and converting this time delay into a distance,
  • Using more advanced multilateration formulas based on a 3D model rather than a 2D model.
unlock-access

Solution...

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

Weight on the Moon Calculator

MoonYour weight is a measure of the amount of gravity exerted on your body by the planet Earth. On planet Earth, gravity has a value of 9.81 N/Kg (Newtons per kilogram). Because the Moon has about one-sixth of the gravity that Earth does, you would weigh less standing on it. On the Moon, gravity has a value of 1.622 N/Kg.

We can hence use the following formula to calculate your weight on the Moon:
weight-on-the-Moon-formula

For this challenge, we will write a short Python program, based on the Input / Process / Output model. Our program will:

  1. INPUT:
    Ask the user to input their weight in kg and store this value in a variable called weightOnEarth.
  2. PROCESS:
    Apply the formula to calculate the equivalent lunar weight and store it in a variable called weightOnMoon.
  3. OUTPUT:
    Display the weight on the Moon on screen.

Python Code


Your Task:


Complete the above code to calculate and output the weight of the end-user on all of the following planets:

Planet / Celestial Body Gravity (in N/Kg)
Moon 1.622
Mercury 3.7
Venus 8.87
Mars 3.711
Jupiter 24.79
Saturn 10.44
Uranus 8.69
Neptune 11.15
unlock-access

Solution...

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

Lissajous Curve Tracing Algorithm

Lissajous curves are a family of curves described by the following parametric equations:

Lissajous-Parametric-Equations

Lissajous curves have applications in physics, astronomy, and other sciences. Below are a few examples of Lissajous curves that you will be able to reproduce in the Python Trinket provided below by changing the values of constant A and B in the Python code.

Lissajous Curves

Lissajous Curves

Lissajous Curve using Python Turtle


Spirographs?

When tracing different Lissajous curves, you will notice that these curves are enclosed in a rectangular shape.

Spirographs are very similar to Lissajous curve but instead of being enclosed by rectangular boundaries, spirographs are generally enclosed by a circular boundary.

You can trace your own spirographs using Python Turtle by completing this Python Turtle challenge.

Rose Curves


Your task is to adapt the above Python script to draw different Rose curves. You can find out more about rose curves and about their parametric equations on the following wikipedia page.

rose-curves-parametric-equations

rose-curves

unlock-access

Solution...

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

The Honeycomb Challenge

honeycomb-pattern-300Honeycomb is a structure of hexagonal cavities (cells of wax), made by bees to store honey and eggs.

In this challenge we will use a set of iterative algorithms to draw a honeycomb pattern.

First, we will create a function to draw a single hexagonal cavity. Our function called drawCavity() will take three parameters:

  • x – the x coordinates to position the hexagon.
  • y – the x coordinates to position the hexagon.
  • edgeLength – the length in pixels of an edge of the hexagon.

honeycomb-cavity

We will then need to use some nested for loops in order to tessellate the hexagonal cell to recreate a 2D honeycomb pattern.
honeycomb

Python Code


We have started the code for you, using Python Turtle. You will need to complete this code further to complete the pattern fully.

unlock-access

Solution...

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

Sudoku Generator Algorithm

Your task is 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.

Sudoku?


A Sudoku game is number-placement puzzle. The objective 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”, “blocks”, or “regions”) contain all of the digits from 1 to 9. The puzzle setter provides a partially completed grid, which for a well-posed puzzle has a single solution.

Our aim for this challenge is not to generate a Sudoku solver algorithm but instead to create an algorithm to be used by a puzzle setter to produce a well-posed Sudoku grid: a grid with a unique solution. For instance the output of our algorithm could be a grid such as this one:

sudoku-grid

Did You Know?

Sudoku fanatics have long claimed that the smallest number of starting clues a Sudoku puzzle can contain is 17. There are effectively numerous examples of grids with 17 clues that have a unique solution but we have never found a well-posed grid with only 16 clues. This suggests that the minimum number of clues to provide in a grid is 17.

This key fact might be useful to help you solve this challenge more effectively.

Sudoku Solver Algorithm


Your Sudoku Generator algorithm may need to use a Sudoku Solver Algorithm in order to test whether a generated grid is solvable and to check that it only gives a single solution.

The most common type of Sudoku Solver Algorithm is based on a backtracking algorithm used to investigate all possible solutions of a given grid.

You can find an example of such an algorithm by investigating the code provided in this Python Challenge: Sudoku Solver using a Backtracking Algorithm

Extension Task:


Sudoku puzzles are often given a difficulty level such as “Beginner – Intermediate – Advanced – Expert”.

How could your algorithm be adapted to estimate the difficulty level of a Sudoku grid?
Should different algorithms be used to generate Sudoku grids for a specific difficulty level?

Solution


Our solution is based on 5 steps:

  1. Generate a full grid of numbers (fully filled in). This step is more complex as it seems as we cannot just randomly generate numbers to fill in the grid. We have to make sure that these numbers are positioned on the grid following the Sudoku rules. To do so will use a sudoku solver algorithm (backtracking algorithm) that we will apply to an empty grid. We will add a random element to this solver algorithm to make sure that a new grid is generated every time we run it.
  2. From our full grid, we will then remove 1 value at a time.
  3. Each time a value is removed we will apply a sudoku solver algorithm to see if the grid can still be solved and to count the number of solutions it leads to.
  4. If the resulting grid only has one solution we can carry on the process from step 2. If not we will have to put the value we took away back in the grid.
  5. We can repeat the same process (from step 2) several times using a different value each time to try to remove additional numbers, resulting in a more difficult grid to solve. The number of attempts we will use to go through this process will have an impact on the difficulty level of the resulting grid.

Full Python Code


unlock-access

Solution...

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

Chemical Elements Quiz

chemical-elementsThe aim of this challenge is to create a quiz based on the list of chemical elements of the periodic table based on the following requirements:

  • The quiz will include 10 questions.
  • Each question will display the name of an element (e.g. Aluminum) and ask the user to enter the symbol of this element (e.g. Al).
  • For each correct answer the user will score 2 points and for each incorrect answer, the user will lose 1 point.
  • The score cannot go in the negative values.
  • A feedback with the correct answer will be given after each question.
  • The final score (out of 20) will be displayed at the end of the quiz.

Python Dictionary


A Python dictionary is a mapping of unique keys to values. Each key is separated from its value by a colon (:), the items are separated by commas (,), and the whole set of key/value pairs is enclosed in curly braces {}.

For this challenge, we will use a dictionary data structure to store all the chemical elements of the periodic table using the symbol of each element as the key and the name of the element as the value. e.g.

elements = {"Ac":"Actinium","Ag":"Silver","Al":"Aluminum","Am":"Americium", ...}

Each value of a dictionary can be accessed by providing its key as follows (notice the use of square brackets [] to access a value from a dictionary):

print(elements["Al"])

Flowchart


To help you complete this challenge, we have created the flowchart of this quiz algorithm.
chemical-element-quiz-flowchart

Python Quiz


We have started the code for the Chemical Elements Quiz and created the Python dictionary containing all 118 chemical elements of the periodic table.

Your task is to complete the code to implement the full quiz based on the above mentioned requirements.

unlock-access

Solution...

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