More results...

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

HCF and LCM algorithms

In this Python challenge we will write two functions to calculate and return the Highest Common Factor (HCF) and the Lowest Common Multiple (LCM) of two numbers.

Highest Common Factor (HCF)


Note that the HCF is also known as the GCD (Greatest Common Divisor).

To calculate the HCF of two numbers we will write a function based on Euclid’s Division Algorithm. Your function called HCF() will take two parameters and will be based on the following flowchart:
Flowchart-HCF-Function

Python Code


Create the HCF() function on the Python trinket below:

Lowest Common Multiple


Once we have worked out the HCF of two numbers we can easily calculate their Lowest Common Multiple (LCM). The LCM of two numbers a and b is their product divided by their HCF:

LCM(a, b) = ab/HCF(a,b)

Your task is to create a new Python function called LCM() that takes two parameters a and b and returns the LCM of the two numbers using the above formula.

Test Plan


Use the following test plan to test both the HCF() and LCM() functions.

Test # Input Values Expected Output Actual Output
#1 a: 32
b: 24
HCF: 8
LCM: 96
#2 a: 45
b: 30
HCF: 15
LCM: 90
#3 a: 78
b: 24
HCF: 6
LCM: 312
#4 a: 60
b: 20
HCF: 20
LCM: 60
#5 a: 100
b: 21
HCF: 1
LCM: 2100
#6 a: 96
b: 72
HCF: 24
LCM: 288
unlock-access

Solution...

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

Euclid’s Division Algorithm

Euclid’s division algorithm is used to calculate the Highest Common Factor (HCF) of two positive numbers. It is based on Euclid’s division lemma and can be implemented in just a few lines of high level code. You can read more about this algorithm on this page.

Euclid’s Division Algorithm: Pseudocode

INPUT a #The largest of two numbers
INPUT b #The smallest of two numbers
WHILE b > 0
   temp = b
   b = a MOD b
   a = temp
END WHILE
OUTPUT a

Trace Table


Do get a better understanding of how this algorithm works we will complete the following trace tables assuming that the two input values a and b will be a = 32 and b = 24. The output (Highest Common Factor) of this program should be 8.

Complete the trace table below to find out if this algorithm will produce the required output.

 Line Numberabtempb > 0?OUTPUT
132
224
3True

Python Code


You can now create a function called calculateHCF() that takes two parameters, a and b and returns the HCF of these two numbers using Euclid’s division algorithm.

To improve your code, you should make it work even when number b is greater than number a.

Test Plan


Test your function using the following test plan:

Test # Input Values Expected Output Actual Output
#1 a: 32
b: 24
8
#2 a: 45
b: 30
15
#3 a: 78
b: 24
6
#4 a: 60
b: 20
20
#5 a: 100
b: 21
1
#6 a: 96
b: 72
24
#7 a: 72
b: 96
24

Tagged with:

Input, Output & Storage Devices: Quiz!

computer-hardwareComputers hardware consists of all the components that you will find inside the computer (Motherboard, CPU, RAM, graphic card, sound card, network card, etc.) as well as all the peripherals/devices than you can plug to a computer.

Peripherals are often categorised into three types:

  • Input Devices,
  • Output Devices,
  • Storage Devices.

  • input-output-devices-2

    Input Devices Output Devices Storage Devices
    Mouse
    Keyboard
    Microphone
    Webcam
    Scanner
    Barcode Reader
    Sensors
    Chip & Pin Card Reader
    Magnetic Stripe Card Reader
    Touchpad
    Game Controller
    Joystick
    Screen/Monitor
    Projector
    Speakers
    Headphones
    Printer (Inkjet or Laserjet)
    3D Printer
    Actuators
    LED
    Magnetic Hard drive
    SSD Hard drive
    USB Key
    CD Drive
    DVD Drive
    Bluray Disc/Drive
    SD Card Reader

    input-output-devices-1

    Take the Quiz! (open full screen)


ASCII Quiz Challenge

ASCII Code


The ASCII code (Pronounced ask-ee) is a code for representing English characters as numbers, with each character assigned a number from 0 to 127. For example, the ASCII code for uppercase A is 65. The extended ASCII contains 256 characters (using numbers from 0 to 255).

To see a list of the most useful ASCII codes, you can download our simplified ASCII helpsheet.

keyboard
Each character that appears on your keyboard has a unique value. This includes the 26 lowercase letters & 26 uppercase letters of the alphabet, the number digits from 0 to 9 and a range of punctuation signs and special characters.

Take the Quiz! (open full screen)


chr() and ord() functions

Using Python, you can easily access ASCII values of a character using the ord() function. And vice-versa, the chr() function is used to retrieve the character matching a given ASCII value. For instance:

  • ord(“A”) returns 65
  • chr(65) returns “A”

ASCII Quiz in Python

Your Python challenge consists of recreating the above game where the user tries to guess the ASCII value of different characters randomly selected. The difference between the user’s guess and the actual ASCII value of the character being displayed is used to decrement a life score.

The user starts the game with a life score of 255 and tries to guess as many ASCII values as possible before reaching a life score of 0. Any correct answer (exact ASCII value guessed) automatically resets the user’s life score to 255!

unlock-access

Solution...

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

Prolog – Food Web Challenge

Prolog is a language built around the Logical Paradigm: a declarative approach to problem-solving.

There are only three basic constructs in Prolog: facts, rules, and queries.

A collection of facts and rules is called a knowledge base (or a database) and Prolog programming is all about writing knowledge bases. That is, Prolog programs simply are knowledge bases, collections of facts and rules which describe some collection of relationships that we find interesting.

So how do we use a Prolog program? By posing queries. That is, by asking questions about the information stored in the knowledge base. The computer will automatically find the answer (either True or False) to our queries.

Source: http://www.learnprolognow.org/

Knowledge Base (Facts & Rules)


Check the following knowledge base used to store the information that appears on a food web:

/* Facts */
plant(grass).
plant(berries).
plant(nuts).

insect(caterpillar).
insect(butterfly).

animal(squirrel).
animal(goldfinch).
animal(fox).
animal(snake).
animal(frog).
animal(eagle).
animal(X) :- insect(X).

insectivore(frog).
insectivore(goldfinch).  

eats(caterpillar,grass).
eats(butterfly,berries).
eats(goldfinch,berries).
eats(squirrel,nuts).
eats(fox,squirrel).
eats(fox,goldfinch).
eats(snake,goldfinch).
eats(snake,frog).
eats(eagle,frog).
eats(eagle,snake).
eats(eagle,goldfinch).
eats(X,Y) :- insectivore(X), insect(Y).         

/* Rules */
herbivore(X):- eats(X,Y), plant(Y).
carnivore(X):- eats(X,Y), animal(Y).
omnivore(X):- herbivore(X), carnivore(X).

predator(X,Y):- eats(X,Y).
prey(X,Y):- eats(Y,X).

pyramid(X,Y):- prey(Y,X).
pyramid(X,Y):- prey(Z,X), pyramid(Z,Y).

Queries


We can now query this database. For each of the queries listed below, what do you think the computer will return?

True or False Queries:
The following queries would return either True or False.

?-herbivore(butterfly).
?-herbivore(fox).
?-omnivore(goldfinch).
?-predator(fox,squirrel)
etc.

Other Queries:
The following queries would return a solution which could be either:

  • A unique value
  • A list of values
  • False if no solution can be found
?-animal(X)
?-herbivore(X).
?-predator(goldfinch,X).
?-pyramid(fox).
etc.

Your Task:


Use a range of queries, similar to the one above to interrogate the knowledge base and complete the food web provided below.

To run your queries you will need to use the online Prolog environment:
https://swish.swi-prolog.org/p/Food-Web-Prolog.pl

Here is the template for the food web for you to complete:
prolog-food-web

Tagged with:

Logic Gates Diagrams (Whiteboard)

QuestionAnswer
Draw the logic gates diagram for the following Boolean expression:

Next Question
Next Question

Scratch – Sprite Movement using a Touchscreen

Many tutorials on how to create a game in Scratch will be based on using the arrow keys to control the main sprite. This is a great approach indeed but is not suitable if you are designing the game toe be used on a tablet or smartphone. In this case, your input device to control the main sprite is not the keyboard but the touchscreen.

The following short tutorial will show you how you can control the movement of your sprite (in this case the cat) using a touchscreen. The idea will be to create two other sprites/buttons called Arrow_Left and Arrow_Right that, when clicked using a mouse or tapped using a touchscreen will tell the cat sprite to move in the relevant direction.
scratch-touchscreen-sprite-movement
You can recreate this code online using the scratch website.

Step 1: Right ArrowStep 2: Left ArrowStep 3: Main SpriteStep 4: Up & Down

Step 1: Arrow_Right Sprite


scratch-new-sprite
You will need tot create a new sprite and use the arrow sprite from the scratch library.
scratch_arrow_sprite

You should rename this sprite “Arrow_Right”.

You will then need to add the following code to this sprite to detect when the user clicks or taps on this sprite:
scratch-arrow-right-code

Step 2: The Arrow Left


Repeat the instructions from Step 1 to create another arrow sprite and call it “Arrow_Left”. The code for this new sprite will be as follows:
scratch-arrow-left-code

You will also need to change the costume of this sprite to show an arrow pointing to the left:
scratch-arrow-costume

The main sprite (in this case the cat, will need to move left or right when it receives the messages “left” and “right”. To do so we will use the following code (on the cat sprite):
scratch-cat-sprite-left-right
You can repeat the above steps to create an Arrow_Up and a Arrow_Down sprite if it is relevant to your game.

Thank You Medical Staff and Key Workers!

During the coronavirus pandemic, the rainbow has become a symbol of gratitude for the medical staff working in hospitals as well as all the other key workers who carried on working to provide essential services to their community.

All over the UK, children have drawn or painted colourful rainbows and have displayed them on their windows or front doors.

In this challenge, we will use some python code to draw a rainbow and a “Thank You” message to all medical staff and key workers.

This is what the output of our code should look like:
thank-you-medical-staff-and-key-workers

Your Task


We have written the code using Python Turtle but it does not produce the expected outcome.

Could you:

  • Change lines 20 to 28 to make sure the code displays the colours of the rainbow in the right order
  • Change lines 30 to 35 to make sure the stars and text are of the right colours.

The output of your code should be the same as the above picture.

Extension Task


You can tweak this code further to change the message or improve the overall look and feel further for instance by adding more stars and playing with the colours used to display the text.

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 Luminance and Contrast Ratio

The luminance of a colour is a measure used to describe the perceived brightness of a colour. It is possible to calculate the luminance of a colour based on its RGB colour code.
colour-luminance-values

So let’s consider an algorithm that collects an RGB colour code as an input, using the (255,255,255) format. The algorithm will then convert these R, G, B values to a 0 to 1 scale as follows:
colour-luminance-RGB-conversion

New R1,G1 B1 values are then calculated using the following rules:
colour-luminance-formula-Red
colour-luminance-formula-Green
colour-luminance-formula-Blue

Finally, the luminance value of the colour can be calculated using the following formula:
colour-luminance-RGB-formula

The reason such complex formulas are necessary to calculate the luminance (“perceived brightness”) of a colour is partly because our eyes’ perception of the brightness of a colour is not linear (it is not directly proportionate to the number of photons being emitted by a computer screen). Effectively our eyes perceive more levels of light in dim conditions, and less in brighter conditions.

Luminance Function


Your first task is to write a function called luminance() that takes 3 parameters r, g and b corresponding to the RGB values of a colour (integer values between 0 and 255). Your function will use the above algorithm to calculate and return the luminance of the given colour.

You can use the trinket at the bottom of this page to write the Python code for this fucntion.

Contrast Ratio


The contrast ratio defines how easy a human eye recognises text or images on a coloured background.

  • The contrast ratio is a numerical ratio between 1:1 and 21:1.
  • To be easily readable, the contrast ratio between the text colour and the background colour must be at least 7:1.
  • A contrast ratio of at least 4.5 may suffice for larger text.

contrst-ratio-low-medium-high

To calculate the contrast ratio between two colours (e.g. font/text colour and background colour) you must first calculate the luminance of both colours and identify which colour is the lightest colour and which colour is the darkest colour. You can then use these luminance values (labelled Llight and Ldark) to calculate the contrast ratio as follows:
contrast-ratio-formula

Contrast Ratio Function


Your second task is to write a function called contrastRatio() that takes 6 parameters corresponding to the RGB values of two colours (integer values between 0 and 255). Your function will work out the luminance values of both colours, identify the lightest of the two colours and use the above formula to calculate and return the contrast ratio between these two colours.

Test Plan


Once your code is complete, check that it works as expected using the following four tests:

Test # Input Values Expected Output Pass/Fail?
#1 (255,255,255)
(0,0,0)
Luminance: 100%
Luminance: 0%
Contrast Ratio: 21
#2 (148, 57, 173)
(174, 84, 199)
Luminance: 12.24%
Luminance: 19.46%
Contrast Ratio: 1.42
#3 (148, 57, 173)
(209, 157, 223)
Luminance: 12.24%
Luminance: 43%
Contrast Ratio: 2.78
#4 (148, 57, 173)
(245, 232, 248)
Luminance: 12.24%
Luminance: 83.9%
Contrast Ratio: 5.16

Magic Trick Algorithm

playing-cardsIn this blog post we are investigating whether we can teach a computer how to perform a magic trick.

Algorithm


If you want a computer to perform a specific task you need to provide this computer with a clear set of instructions that the computer will repeat, one instruction at a time. We call such a set of specific instructions an algorithm.

One of the key characteristic of an algorithm is that the instructions are given in a specific order, forming a sequence of instructions. When the computer will complete your algorithm, it will complete each instructions one instruction at a time in the order they appear on the algorithm. We call this sequencing, a key concept of computer algorithms.
sequencing-label

When designing an algorithm, we can either write our instructions as a list (Pseudocode) or we can use a more visual representation of our algorithm using a flowchart.

Magic Trick Algorithm


We have implemented a magic trick algorithm based on a small deck of cards. When you press the start button below, the computer will follow the sequence of instructions from this algorithm to perform the magic trick.

Let’s see if the computer can perform this magic trick successfully:


Click on the button below to start the magic trick!

Magic Trick Algorithm/Flowchart


The flowchart for this algorithm will help you work out how the actual card trick works!
magic-trick-flowchart
Click on the above flowchart to open in a new window.

Tagged with: