More results...

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

Fraction Simplifier

This challenge consists of writing a program that asks the end-user to enter a fraction (numerator and denominator) and output the matching reduced fraction when the fraction can be reduced.

To see what this program should do in action you may want to try fractionsimplifier.com.

fraction_numerator_denominator

To simplify a fraction your program will need to find the greatest common divisor (aka greatest common factor) of the numerator and denominator that will have been entered by the end user. Then, your program will divide the numerator and denominator of the fraction by this number.

fraction

To find out if a number is a factor of the numerator you will need to check that the remainder of the numerator divided by this number is null (=0):

  • For instance 3 is a factor of 24 because 24 mod 3 = 0.
  • remainder_24

  • Whereas 5 is NOT a factor of 32 because 32 mod 5 = 2 != 0.
  • remainder32

Extra tip: A factor of a number is always lower or equal to this number.

Your Challenge:


Complete the code below to find the greatest common factor of both the numerator and denominator entered by the end-user and use it to output the simplified fraction.

unlock-access

Solution...

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

Area Calculator

For this challenge we are going to use a Python script to calculate the area in square meters of two different flats.

To do so we will write a computer program that will add up all the areas of each room.

Most rooms have a rectangle shape. So we will first define a function that takes two parameters: width and length and return the area of the rectangle using the following formula:

area = width * length

Let’s use this formula to calculate the area of this small flat:Flat_0

Your Challenge


Tweak the code above to calculate the area of the following two flats: (Click on each picture to zoom in).
Flat_1

Flat_2

Challenge #2


The area of a right-angled triangle can be calculated as follows:
triangle
area = width * length / 2

Add a new function called getTriangleArea to return the area of a right-angled triangle using two parameters: width and length.

Use both the getRectangleArea and getTriangleArea functions to calculate the area of this room:
flat_4

Challenge #3:


Use your code to calculate the area of this small mansion (Click on picture to zoom in):
flat_5

unlock-access

Solution...

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

3D Challenge

3DCubeThe aim of this challenge is to draw a cube in 3D and to make it rotate on the screen.

Drawing 3D shapes on a screen (2D) requires some mathematical formulas to convert 3D (x,y,z) coordinates into 2D coordinates (x,y). This conversion, also known as “oblique projection” is based on the following formulas:
oblique-projection-formulae

This is a great application of trigonometry, especially of the SOCATOA formulas!

socatoa

cosine

sine

(Read more about trigonometric formulas.)

A 3D rotation against an axis (X, Y or Z axis) also requires some complex mathematical formulas. To apply a 3D rotation we can use the rotation matrix as follows:
3d-rotation-matrix

Our Solution:


To decide the angle and axis of rotation we use the position of the mouse pointer.
The X coordinate of the mouse pointer becomes the angle of rotation against the Y axis.
The Y coordinate of the mouse pointer becomes the angle of rotation against the X axis.
In this example we did not implement a rotation against the Z axis.

Your Task


3d-houseAdd more edges to the code given above to create a full house including a roof, a front door and a window.
unlock-access

Solution...

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

Mastermind Challenge

mastermind
Have you ever played the board game “Mastermind”?

If you are not too sure about the rules of this game, you should first check this page.

For this challenge we are going to create this game of mastermind where the end-user plays against the computer. The end-user’s role is to guess the choices of 4 colours made by the computer.

Learning Objectives


By completing this game we are using all our coding skills using nested loops and IF statements.

We are also learning about how flowcharts can be used to describe a complex algorithm.

Flowchart


Can you create the flowchart for this computer game yourself?
Give it a try. Once done, compare your flowchart with our flowchart:
Mastermind-Thumbnail
Note that there is often more than one approach to solve a problem.

Code


Use either your flowchart or the one given above and translate it into programming code using Python.

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: Reading a text file

Learning Objectives

In this challenge we are going to focus on accessing a text file in Python to read the content of the file line by line.

Challenge

Your first challenge consists of writing a Python script that will read the following text file, one line at a time and display the content of each line on screen.


TextFile
My Playlist.txt

To read the content of a text file line by line we are going to use a for loop that will loop through and extract each line of the text file one at a time. It will stop looping only once the it will have reached the last line.

Check this animation that explains this process:
Reading-Text-File-Animation-s

When the text file uses a CSV format (Comma Separtred Values), each line contains several values separated using a special character, often a comma or a semi-colon. In this case we can use the split() method to extract each value of each line and store them in a list.

Check this animation that explains this process further:
Reading-CSV-File-Animation-s

Solution

The solutions below contains 5 main steps:

  1. Step 1: Open the text file using the open() function. This function takes two parameters: The name of the file (e.g. “playlist.txt”) and the access mode. In our case we are opening the file in read-only mode: “r”.
  2. Read through the file one line at a time using a for loop.
  3. Split the line into an array. This is because in this file each value is separated with a semi-column. By splitting the line we can then easily access each value (field) individually.
  4. Output the content of each field using the print method.
  5. Once the for loop is completed, close the file using the close() method.

 

Main Access Modes when opening a file with the open() function.

Mode Description
r Opens a file in read only mode. This is the default mode.
r+ Opens a file for both reading and writing.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
w+ Opens a file for both writing and reading. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
a Opens a file for appending. The file pointer is at the end of the file. So new data will be added at the end of the file. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Your Challenge


Use what you have learnt in this blogbpost to complete these challenges:
My mp3 playlist(Reading a text file using Python) US Population(Reading a text file using Python)

Python Tip: Validating user input as number (Integer)

In most of your Python programs you will want to interact with the end-user by asking questions and retrieving user inputs.

To do so you can use the input() function: e.g.

username=input("What is your username?")

Sometimes you will need to retrieve numbers. Whole numbers (numbers with no decimal place) are called integers. To use them as integers you will need to convert the user input into an integer using the int() function. e.g.

age=int(input("What is your age?"))

This line of code would work fine as long as the user enters an integer. If, by mistake, they enter letters or punctuation signs, the conversion into an integer will fail and generate an exception (error) and the program would stop running.

To validate the user entry and ensure that is a number it is possible to catch this exception when it occurs using the try…except….else block as follows:

try:
    value=int(input("Type a number:"))
except ValueError:
    print("This is not a whole number.")

See how we can use this approach to define our own function (called inputNumber()) to ask for a number. This new function can then be used instead of an input() function whenever we expect the user to enter a whole number. This function uses the try…except….else block within a while loop so that it keeps asking the user to enter a number till the user gets it right.

Final Code:

def inputNumber(message):
  while True:
    try:
       userInput = int(input(message))       
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput 
       break 
     

#MAIN PROGRAM STARTS HERE:
age = inputNumber("How old are you?")

My mp3 playlist

Learning Objectives


In this challenge we are going to focus on accessing a text file in Python to:

  • Read the content of the file line by line,
  • Append data at the end of the file,
  • Write into a new text file.

To complete these challenges we recommend you to use Coding Ground which let you code online and use multiple files. You will first need to create a text file to copy the content of the playlist (from the text file given below)

codingground

Challenge #1


Your first challenge consists of writing a Python script that will read the following text file, one line at a time and display the content of each line on screen.


TextFile
My Playlist.txt


As you are willing to complete this challenge we assume that you already have some good Python skills. To learn more about accessing text files in Python, you will first need to do some research on the Internet.

Challenge #2


Your second challenge consists of opening the text file with Python in “write” mode to add the following song at the end of the playlist:

“Happy” by Pharrell Williams – Duration: 3:52

You will need to research the Intenet on how to write at the end of a text file.

Challenge #3


For your third challenge you will edit the playlist so that the song “Happy” by Pharrell Williams appear in third position.

Tagged with: ,

Countdown

countdown_animatedThe aim of this blog post is to create a countdown timer that will display the numbers on screen using a 7-segment display. A lot of electronic devices use this approach to display numbers on a LED or LCD screen. (Watch, alarm clock, calculator etc.)

First we need to investigate how the 7-segment display works. You will find this page quite useful.

Typically 7-segment displays consist of seven individual coloured LED’s (called the segments). Each segment can be turned on or off to create a unique pattern/combination. Each segment is identified using a letter between A to G as follows:

7segments

The following truth table shows which segments need to be on to display the digits from 0 to 9:

Digit A B C D E F G
tmp-0 1 1 1 1 1 1 0
tmp-1 0 1 1 0 0 0 0
tmp-2 1 1 0 1 1 0 1
tmp-3 1 1 1 1 0 0 1
tmp-4 0 1 1 0 0 1 1
tmp-5 1 0 1 1 0 1 1
tmp-6 1 0 1 1 1 1 1
tmp-7 1 1 1 0 0 0 0
tmp-8 1 1 1 1 1 1 1
tmp-9 1 1 1 1 0 1 1

Your Challenge

The code below is used to display a countdown timer counting from 5 to 0 and using the 7-segment approach to display the numbers.

Your challenge consists of using the truth table given in this post to start your countdown from 9 (instead of 5).

Challenge #2:


With 7 segments there are 128 possible symbols. Some can be used to represent letters. For instance:

tmp-10tmp-11tmp-12tmp-13tmp-14tmp-15

Tweak the code above to write a message using the 7-segment display.

Start with the following message “Hello” (HELLO)

Morse Code Encoder

The aim of this challenge is to create a Morse code converter that lets the user enter any message. The program should then display the message in Morse code. To complete this challenge you will need to know how Morse code works. If the information given below is not clear enough you can find out more about Morse code on this wikipedia page.

Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment.

Each character (letter or numeral) is represented by a unique sequence of dots and dashes. The duration of a dash is three times the duration of a dot.

For this challenge we will be using the international Morse code as follows:
Morse_code

Learning Objectives


By completing this challenge we are going to learn about Python dictionaries.
In Python, a dictionary consists of pairs (called items) of keys and their corresponding values.

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:
PythonDictionary

myDictionary = {"Red": "#FF0000", "Green": "#00FF00", "Blue": "#0000FF"}
print("The colour code for Green is:")
print(myDictionary["Green"])

btnTryCodeOnline

Morse Code Encoder


Check the code below to encore your own message into Morse code:

Challenge #1:


Complete the code above to add the Morse code for number digits between 0 and 9 as follows:
Morse_code_numbers

Challenge #2: Morse Code Decoder


Write a program that enables you to decode a message written in Morse code. For instance, your program should be able to decode the following message:
… — … -.-. –.- -.. – .. – .- -. .. -.-. .– . .- .-. . … .. -. -.- .. -. –. ..-. .- … –

Challenge #3: Sending Light Signals


Morse_code_signalsCheck the following code used to simulate a lamp going on and off to reproduce an SOS call in Morse code: … — …

Combine this code with the code from the Morse code encoder to create light signals in Morse code. Remember the rules of Morse code:

  • Each character (letter or numeral) is represented by a unique sequence of dots and dashes.
  • The duration of a dash is three times the duration of a dot.
  • Each dot or dash is followed by a short silence, equal to the dot duration.
  • The letters of a word are separated by a space equal to three dots (one dash).
  • The words are separated by a space equal to seven dots.


unlock-access

Solution...

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

Home Alone – Kevin is not here!

First, let’s watch this short video clip from the movie Home Alone 2.

This video clip highlights a typical case of recursion.

Recursive Functions


A recursive function is a function which calls itself.
To make sure that a recursive function does not loop indefinitely it needs a stopping condition to check if a condition is met: If it is, it should stop calling itself.

In this challenge we are writing a recursive function that asks the person standing next to us to “pass this bag to Kevin”. Each person in the queue forwards this message by calling the same function. However if we reach the end of the queue or if we reach Kevin then we stop asking. So in this case we have two conditions that can stop the recursion: we reach the end of the queue/list or we reach Kevin.

Give this to Kevin: Recursive Function


For more examples based on recursive functions, check this post.