More results...

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

Multi-threading in Python

multi-threadingIn this blog post we will investigate how to implement concurrent processing in a Python program to allow multiple processes to be executed concurrently.

To do so will create and run multiple threads in our program and will need to use Python 3 and the threading library.

So what’s a thread and what is multi-threading?
In Python, a thread is a sperate process / flow of execution. Running multiple threads in a program allows multiple tasks to progress concurrently.

Let’s investigate one application of multi-threading using a basic computer program used to find very large prime numbers.

Prime Number Finder

In this example, we will create a class called PrimeNumberThread that derives from the Thread class of the threading library.

This class/thread will be used to find very large prime numbers from any given starting position (e.g. Checking any number greater than 100,000,000,000,000 one by one to see if they are a prime number or not).

We will then run three threads concurrently, each thread starting with a different starting position .e.g.

  • Thread 1 will look up for prime numbers, starting from number 100,000,000,000,000
  • Thread 2 will look up for prime numbers, starting from number 300,000,000,000,000
  • Thread 3 will look up for prime numbers, starting from number 500,000,000,000,000

As soon as a thread finds a prime number, it will display it on screen. All three threads will be working concurrently. You can run the following code to see the output generated by all three threads…

The above program is a very brief introduction to what is meant by running multiple threads in a computer program. There are a lot more concepts linked to multi-threading and you can find out more about these concepts by reading through this tutorial on multi-threading with Python.

The Legend of Pachacuti’s Golden Shield

golden-shieldA few weeks ago, a group of British trekkers stumbled upon the remains of what is believed to be an undiscovered Inca temple in the middle of the Peruvian rainforest. One of their most unexplained discoveries is a collection of 12 engraved slates and a parchment representing a map of the newly discovered site. The slates are engraved with some sort of code. We believe these 12 slates could help locate the 12 pieces of Pachacuti’s Golden Shield.

Pachacuti’s was a famous Inca ruler in the 15th century who transformed the kingdom of Cusco in the Inca empire. For many decades archaeologists from around the world have been excavating many sites in the Urubamba Valley hoping to locate the Pachacuti’s Golden Shield, a uniquely carved shield of inestimable value.

It would appear that the shield may have been smashed into 12 pieces and each of these may have been hidden on the site of this newly discovered temple. We are asking for your help to see if you can work out the exact location of the 12 pieces of Pachacuti’s Golden Shield using the code from the 12 slates and the parchment/map found alongside these slates. We are counting on you! Good luck!

Pachacuti’s Golden ShieldOpen in New Window
Pachacuti’s Golden ShieldOpen in New Window
unlock-access

Solution...

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

The School Lockers Puzzle

On the first day of school, the principal of Locker High school decides to conduct an experiment. The school has exactly 1,000 students and 1,000 lockers all lined up alongside the main corridor of the school.
school-lockers-puzzle

  1. The principal asks the first student to walk down the main corridor of the school to close all the lockers.
  2. The principal then asks the second student to walk down the main corridor and open every other locker.
  3. The principal then asks the third student to walk down the main corridor and either open every third locker if it is closed, or close it if it is open.
  4. The fourth student will then repeat the same process for every fourth locker.
  5. And so on, till the last of the 1,000 students repeats this process for every 1,000th locker, so in fact, just opening the 1,000th locker if it is closed, or closing it if it is already open.

At the end of this experiment the principal decides to count the number of lockers which are closed.

It is possible to solve this puzzle using your mathematical skills, however in this challenge, your task is to implement a computer program (using Python) to simulate this experiment and at the end, count and output the total number of lockers which are closed.


We have started the code and completed three sections of the code as follows:

Step 1:
We start by initialising an array/list of 1,000 values representing the 1,000 lockers:

  • 0 will represent an open locker,
  • 1 will represent a closed locker.

“To start with all the lockers a open!”

lockers = [0] * 1000

Step 2:

“The first student walks down the corridor to close all the lockers!”

for i in range(0,1000):
  lockers[i] = 1

A similar approach will need to be implemented to reproduce the actions of the remaining 999 students! This will be your task!

Step 3:

“At the end, the principal of the school counts how many lockers are closed!”

total = 0 
for i in range(0,1000):
   total = total + lockers[i]
   
print("Total number of lockers closed: " + str(total))

Python Code

You will need to complete the following code to solve this challenge:

The Principal’s padlock

The solution to the above challenge is the combination of the principal’s padlock. Use the output of your code to see if you can unlock this padlock!

unlock-access

Solution...

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

2D Dice Grid Scoring Algorithm

This challenge is based on a 4×4 grid of dice (16 dice in total). Each game starts by shaking the grid to generate a new grid of 16 values.
2D-dice-grid

All dice are 6-sided dice, generating random values between 1 and 6 when the grid is shaken. The grid can be simplified by showing the actual dice values:
2D-dice-grid-values

Once the new grid is set, its score can be calculated by identifying specific patterns as follows:

  1. Start with a score of 0,
  2. If all four corners are even numbers, add 20 pts to the score,
  3. If all four corners are odd numbers, add 20 pts to the score,
  4. If all four dice on a diagonal are even numbers, add 20 pts to the score,
  5. If all four dice on a diagonal are odd numbers, add 20 pts to the score,
  6. If all four dice on on any row are even numbers, add 20 pts to the score,
  7. If all four dice on on any row are odd numbers, add 20 pts to the score,
  8. If all four dice on on any column are even numbers, add 20 pts to the score,
  9. If all four dice on on any column are odd numbers, add 20 pts to the score,
  10. Add to the score the total value (sum) of all 16 dice.

So for example, with the above grid, we can calculate the score of the grid as follows:
2D-dice-grid-score

Python Implementation

To help you with this challenge we have started the code for you by creating 4 functions to:

  • Generate/shake the grid of 16 dice.
  • Display the 4×4 grid on screen.
  • Check if a number is even.
  • Check if a number is odd.

We have also implemented the first section of the scoring algorithm, by initialising the grid score to 0 and by checking if all four corners are even. If so the score is increased by 20pts.

Your task is to complete the following code to implement the full scoring algorithm using the 10 rules mentioned above.

unlock-access

Solution...

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

Tagged with:

Diagonal Difference Calculator

Let’s consider a square matrix of n x n. (n columns and n rows). The diagonal difference of a square matrix is the absolute difference between the sums of its diagonal.

Let’s look at an example based on the following 3 x 3 square matrix:
sqaure-matrix
Here is how we would calculate the diagonal difference for this matrix:
diagonal-difference

Python Challenge

We have created a Python script that asks the user to input the dimension n of a square matrix (any positive integer value). Our python scripts generates a n x n matrix using random values and displays it on screen as a 2D grid.

Your task is to complete this script to automatically calculate the diagonal difference of the given matrix. (Make sure this value is always a positive value!)

Python Code

Extension Task #1

Your first extension task is to create an additional function to calculate the sum of the 4 corner values of the square matrix:
square-matrix-four-corners

Extension Task #2

Your second extension task is create an additional function to calculate the average value of all values stored in the matrix.
square-matrix-average-value

unlock-access

Solution...

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

Wind Speed Conversions and the Beaufort Scale

weather-vaneBefore going to sea, any sailor should check the marine weather forecast to check on different aspects of the weather including the direction and strength of the wind (wind speed).

The wind speed can be measured using different units such as mph (miles per hour), km/h (km per hour) but sailors tend to prefer to use knots. A knot represents a speed of 1 nautical mile per hour, and a nautical mile is exactly 1,852 meters!

The Beaufort wind force scale was introduced in 1805 by a Royal Navy officer, Francis Beaufort. It relates wind speeds to observed conditions at sea or on land. Nowadays, the scale contains thirteen values (from zero to twelve): A force 0 wind represents very calm wind conditions whereas a force 12 wind represents a Hurricane-force wind!

Here is the full Beaufort scale:

Beaufort Wind Force Scale
Force Description Wind speed Wave height Sea conditions Land conditions
0 Calm < 1 knot 0 ft (0 m) Sea like a mirror Smoke rises vertically.
1 Light air 1–3 knots 0–1 ft Ripples with appearance of scales are formed, without foam crests Direction shown by smoke drift but not by wind vanes.
2 Light breeze 4–6 knots 1–2 ft Small wavelets still short but more pronounced; crests have a glassy appearance but do not break Wind felt on face; leaves rustle; wind vane moved by wind.
3 Gentle breeze 7–10 knots 2–4 ft Large wavelets; crests begin to break; foam of glassy appearance; perhaps scattered white horses Leaves and small twigs in constant motion; light flags extended.
4 Moderate breeze 11–16 knots 3.5–6 ft Small waves becoming longer; fairly frequent white horses Raises dust and loose paper; small branches moved.
5 Fresh breeze 17–21 knots 6–10 ft Moderate waves taking a more pronounced long form; many white horses are formed; chance of some spray Small trees in leaf begin to sway; crested wavelets form on inland waters.
6 Strong breeze 22–27 knots 9–13 ft Large waves begin to form; the white foam crests are more extensive everywhere; probably some spray Large branches in motion; whistling heard in telegraph wires; umbrellas used with difficulty.
7 High wind,
moderate gale,
near gale
28–33 knots 13–19 ft Sea heaps up and white foam from breaking waves begins to be blown in streaks along the direction of the wind; spindrift begins to be seen Whole trees in motion; inconvenience felt when walking against the wind.
8 Gale,
fresh gale
34–40 knots 18–25 ft Moderately high waves of greater length; edges of crests break into spindrift; foam is blown in well-marked streaks along the direction of the wind Twigs break off trees; generally impedes progress.
9 Strong/severe gale 41–47 knots 23–32 ft High waves; dense streaks of foam along the direction of the wind; sea begins to roll; spray affects visibility Slight structural damage (chimney pots and slates removed).
10 Storm,
whole gale
48–55 knots 29–41 ft Very high waves with long overhanging crests; resulting foam in great patches is blown in dense white streaks along the direction of the wind; on the whole the surface of the sea takes on a white appearance; rolling of the sea becomes heavy; visibility affected Seldom experienced inland; trees uprooted; considerable structural damage.
11 Violent storm 56–63 knots 37–52 ft Exceptionally high waves; small- and medium-sized ships might be for a long time lost to view behind the waves; sea is covered with long white patches of foam; everywhere the edges of the wave crests are blown into foam; visibility affected Very rarely experienced; accompanied by widespread damage.
12 Hurricane force ≥ 64 knots ≥ 46 ft The air is filled with foam and spray; sea is completely white with driving spray; visibility very seriously affected Devastation.

Python Challenge

In this challenge we will write a python script that:

  1. lets the user enter a wind speed in the unit of their choice (mph, km/h, knot)
  2. converts this wind speed in knots and lookup the matching find force,
  3. looks up for the matching wind force from the Beaufort scale,
  4. outputs the wind force and both the matching sea and land conditions

Python Code

You can complete the python code using the following trinket:

unlock-access

Solution...

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

Circle Geometry Functions

In this challenge we will create a library of functions to apply the different formulas based on the geometry of circles.

For each function, you will need to design the algorithm using either Pseudo-code or a flowchart, implement the function using the Python trinket provided below and use another algorithm to test your function.

CircumferenceAreaArcSector: PerimeterSector: AreaChordSegment: PerimeterSegment: Area
circle-circumference
Write a function called getCircumference() that takes one parameter/argument: the radius of a circle.

Your function should calculate and return the circumference (perimeter) of this circle..


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the radius of a circle,
  • Use the getCircumference() function to retrieve the circumference of the circle,
  • Display the circumference of the circle
circle-area
Write a function called getArea() that takes one parameter/argument: the radius of a circle.

Your function should calculate and return the area of this circle..


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the radius of a circle,
  • Use the getArea() function to retrieve the area of the circle,
  • Display the area of the circle
circle-arc
Write a function called getArcLength() that takes two parameters/arguments: the radius and angle of an arc.

Your function should calculate and return the length of this arc..


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the radius of a circle,
  • Ask the user to enter the angle of an arc,
  • Use the getArcLength() function to retrieve the length of this arc,
  • Display the length of the arc.
circle-sector-perimeter

Write a function called getSectorPerimeter() that takes two parameters/arguments: the radius and angle of a sector.

Your function should calculate and return the perimeter of this sector..


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the radius of a circle,
  • Ask the user to enter the angle of a sector,
  • Use the getSectorPerimeter() function to retrieve the perimeter of this sector,
  • Display the perimeter of this sector.
circle-sector-area

Write a function called getSectorArea() that takes two parameters/arguments: the radius and angle of a sector.

Your function should calculate and return the area of this sector..


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the radius of a circle,
  • Ask the user to enter the angle of a sector,
  • Use the getSectorArea() function to retrieve the area of this sector,
  • Display the area of this sector.
circle-chord
Write a function called getChordLength() that takes two parameters/arguments: the radius and angle of a chord.

Your function should calculate and return the length of this chord..


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the radius of a circle,
  • Ask the user to enter the angle of a chord,
  • Use the getChordLength() function to retrieve the lenght of the chord,
  • Display the length of the chord
circle-segment-perimeter

Write a function called getSegmentPerimeter() that takes two parameters/arguments: the radius and angle of a segment.

Your function should calculate and return the area of this segment..


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the radius of a circle,
  • Ask the user to enter the angle of a segment,
  • Use the getSegmentPerimeter() function to retrieve the perimeter of this segment,
  • Display the perimeter of the segment
circle-segment-area

Write a function called getSegmentArea() that takes two parameters/arguments: the radius and angle of a segment.

Your function should calculate and return the area of this segment..


Write an algorithm to test your function.
Your algorithm should:

  • Ask the user to enter the length of the radius of a circle,
  • Ask the user to enter the angle of a segment,
  • Use the getSegmentArea() function to retrieve the area of this segment,
  • Display the area of the segment

Python Code


We have already started the code for you and have completed the function getCircumference() followed by a short algorithm to test this function.

Your task is to complete this Python script to create and test all the functions mentioned above.

Tagged with: ,

Tutankhamun’s Papyrus

The mask of Tutankhamun

The mask of Tutankhamun

The historical era of ancient Egypt spreads over more than 30 centuries during which different pharaoh’s ruled Egypt. One of the most famous pharaoh, Tutankhamun commonly referred to as King Tut ruled from 1334 to 1325 BC. He was the son of the pharaoh Akhenaten and took the throne at the age of eight or nine!

The discovery, in 1922, of Tutankhamun’s nearly intact tomb received worldwide press coverage and sparked a renewed public interest in Ancient Egypt. Within the tomb, more than 5,000 artefacts were discovered including Tutankhamun’s mask which is nowadays one of the most popular symbol of Ancient Egypt.

While conducting some research on the life of Tutankhamun, two eminent Egyptologists from Cambridge University, UK, decrypted some hieroglyphs which led them to believe that one artefact has yet to be found: A papyrus drawn by King Tut himself! They believed the papyrus has been torn apart into 12 pieces and have managed to identify the exact location of all 12 pieces of the ancient papyrus.
papyrus-pieces
The two Egyptologists contacted a team of archaeologists working on an excavation site near the great Pyramid of Giza and were meant fly to Egypt at the end of the month to join them and excavate the 12 parchments. However, they mysteriously disappeared and never reached Egypt. The police found at their home 12 small papyrus with some mysterious codes as well as a map of the archaeological excavation site. We believe these were written by the two archaeologists to encode the exact locations of all 12 pieces of King Tut’s parchment.

Your task is to use your coding skills to identify the exact location of all the 12 pieces of the ancient parchment.
pyramids-200

Tutankhamun’s papyrusOpen in New Window pyramids-200

unlock-access

Solution...

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

Egyptian Numerals Conversions

In this blog post we will investigate how Egyptians used to write numbers (Ancient Egypt civilisation) and we will use an algorithm to convert decimal numbers into Egyptians numerals.

By completing this challenge, we will compare two different numerical notations:

  • Positional Notation (a.k.a Place Value Notation) as used by the decimal system (Hindu-Arabic numeral system)
  • Additive Notation as used by the Ancient Egypt numeral system as well as the Roman numeral system

Positional Notation (a.k.a Place Value Notation)

The notation we use nowadays when writing decimal numbers is based on the Hindu-Arabic numeral systems where each digit of a number has a value corresponding to the value of the digit multiplied by a factor (a power of 10) determined by the position of the digit in the number.

For instance:
place-value-notation

With this number, the least significant digit (on the right: 5) represents units, the next digit (2) represents tens, the next digit (4) represents hundreds and the most significant digit (on the left: 3) represents thousands.

This notation is called a Place Value notation because the value of a digit varies based on its position/place in the number. So, for instance the digit 3 in the above number (3,425) has a value of 3,000 but in the number 2,536 its value is now 30.

Additive Notation

Ancient civilisations such as the Ancient Egypt Civilisation used a different notation to represent numbers. In the additive notation each symbol has a unique value which does not change based on its position in the number. The value of a number if calculated by adding the value of each of the symbols used in this number.

So, let’s investigate the symbols (Hieroglyphs) used in Ancient Egypt to represent numbers:

Symbol/Hieroglyph 𓏺 𓎆 𓏲 𓆼 𓂭 𓆐 𓁨
Value 1 10 100 1,000 10,000 100,000 1,000,000

Using the above symbols we can easily calculate the value of a number as follows:
egyptian-numerals-additive-notation

Using this approach can you convert the following numbers in decimal?


egyptian-numerals-hieroglyphs-1

egyptian-numerals-hieroglyphs-2

egyptian-numerals-hieroglyphs-3

egyptian-numerals-hieroglyphs-4

Online conversions

Use our online convertor to check your answers…

Roman Numerals: Additive and Subtractive Notation

Roman Numerals use an additive notation combined with a subtractive notation.
The symbols used in Roman numerals are as follows:

Symbol M D C L X V I
Value 1,000 500 100 50 10 5 1

roman-numerals-additive-notation

roman-numerals-additive-subtractive-notation
Using this approach can you convert the following numbers in decimal?


roman-numerals-2
roman-numerals-1
roman-numerals-3
roman-numerals-4

Online conversions

Use our online convertor to check your answers…

UPC Barcodes

barcode-640522710850A barcode is a visual representation of data that can easily be read by an optical barcode scanner/reader. Barcodes are used to facilitate and speed up the identification of different types of products. Using a barcode reader speed up the input/data entry process and and is a more reliable method generating less data entry errors than when a product code is entered manually.

There are different types/formats of barcodes such as ISBN barcodes used to identify books/publications or UPC (Universal Product Codes) or EAN (European Article Number) barcodes to uniquely identify products/trade items.

You can visit this wikipedia page to find out a about a range of linear barcodes (1D) and matrix barcodes (2D) such as QR codes.

UPC Encoding

Let’s focus on UPC barcodes. UPC barcodes are widely used in America, Europe, Australia, New Zealand, and other countries for tracking trade items in stores. A UPC barcode is a linear barcode consisting of a series of black and white stripes of different thickness. They are used to encode 12 numerical digits in two groups/segments of 6 digits: the left segment and the right segments.

A UPC barcode is delimited using guards: specific patterns that appear at the start, at the end and also in the middle of the barcode to separate the left and right segment:
upc-barcode-anatomy

With UPC barcodes, the first and last digits are often displayed before and after the left and right hand side guards of the barcode (even though the stripes representing these digits are still within the guards patterns):
UPC-barcode-digits-position

Each numerical digit is encoded using a specific pattern. However the patterns used are different on the left and right segments. This feature is necessary to ensure that barcode readers can read a barcode in both directions (in case a barcode is presented upside down). In fact the patterns used on the right segments for each digit are the exact opposite to the patterns used for the digits on the left segment. Each pattern is seven stripes wide:
upc-barcode-digits

Decoding a barcode

Use the information provided above to decode the following barcodes and check your UPC codes using barcodespider.com to identify the corresponding products.

# Barcode Product UPC?
#1 Raspberry Pi Model 3B
#2 32GB SD Card
#3 Optical Cordless Mouse

Barcode Generator

Check digits

The last digit of a UPC-A barcode is the check digit. A check digit is used to minimise the risk of errors when scanning a barcode. A check digit calculation is used to confirm that a barcode being scanned is valid or not. You can read more about check digit validation on this blog post.