More results...

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

Dice Score Frequency Analysis

two-diceIn this challenge we will use a Python algorithm to perform a frequency analysis of the score obtained when throwing a set of two dice.

Frequency analysis using 1 dice


Let’s consider a single 6-sided dice.

When using single dice, the score of the dice can be any of the 6 values/sides (1 to 6). Each value has an equal probability of 1/6.

The dice experiment can be simulated using a computer algorithm to simulate throwing a dice a 1,000 times and keeping a record of the number of times each of the 6 values appeared. We can then calculate the frequency of each value as a percentage. In theory, each value should have a very similar frequency of around 16.67% (matching the 1/6 probability).

When completing such an experiment in real life, we would mot likely use a tally chart to record the number of occurrences for each of the 6 possible values.
dice-tally-chart

To record our “tallies” in a Python program we will use a dictionary with 6 keys (the 6 values of a dice, from 1 to 6) and for each key, the associated value will be the number of occurrences of when the value appeared.

Here is the Python implementation of our dice experiment (frequency analysis).

Run the above code several times.

  • Do you notice the frequencies changing slightly every time you run this code?
  • Does the experiment confirm the theory: each side having an equal probability, the percentage for each value should be 16.67%?
  • What do you think will happen if, instead of 1,000 iterations you were completing 1,000,000 iterations?
  • Change the value of n in the above code from 1,000 to 1,000,000 and run the code. Does the outcome confirm your prediction?

Using two dice


We are now going to simulate the same experiment, this time using two dice, and recording the total score (by adding the value of both dice). The dice score will be as follows:

Total Score Possible Combinations Probability
2 1+1 1/36 = 2.78%
3 1+2 or 2+1 2/36 = 5.56%
4 1+3 or 2+2 or 3+1 3/36 = 8.33%
5 1+4 or 2+3 or 3+2 or 4+1 4/36 = 11.11%
6 1+5 or 2+4 or 3+3 or 4+2 or 5+1 5/36 = 13.89%
7 1+6 or 2+5 or 3+4 or 4+3 or 5+2 or 6+1 6/36 = 16.67%
8 2+6 or 3+5 or 4+4 or 5+3 or 6+2 5/36 = 13.89%
9 3+6 or 4+5 or 5+4 or 6+3 4/36 = 11.11%
10 4+6 or 5+5 or 6+4 3/36 = 8.33%
11 5+6 or 6+5 2/36 = 5.56%
12 6+6 1/36 = 2.78%

Your Task:


Your task consists of adapting the Python program given above (1 dice experiment) to implement the experiment with two dice and see whether your program produces the expected probabilities for all possible scores from 1 to 12.
unlock-access

Solution...

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

Random Odd and Even Numbers

random-numbersIn this challenge we will focus on using the random library to generate random numbers in Python.

The randint() function is used to generate a random integer (whole number) within a given range.

import random
number = randint(1,100)

The above code would generate a random number between 1 and 100.

The aim of this challenge is to write our own function called randomOddNumber() to generate a random odd number within a given range and a another function called randomEvenNumber() to generate a random even number. Both functions will take two parameters, the lower and higher values of the range.

Random Odd Number Functions


We will investigate three different algorithms to implement the randomOddNumber() function:
Method #1: SequencingMethod #2: IterationMethod #3: Selection
The first method is based on a sequencing algorithm.
sequencing-label
Here is the approach we will use:
To generate an odd number, let’s say between 0 and 100, we will first generate a random number between 0 and 49, then multiply this number by 2 (this will hence become an even number between 0 and 98) and finally we will add 1 to make it an odd number (between 1 and 99).

Python Code:

The second algorithm is based on a while loop (a form of iteration).
iteration-label
With this approach we are generating a random number between 1 and 100. We will repeat this process as long as the number generated is even (not odd). A number is even if the remainder of dividing this number by two is zero.

Python Code:

Our third approach will be based on using an IF statement, a form of selection.
selection-label
We will generate a random number, check if this number is odd or even by checking whether the remainder of dividing this number by two is zero (for an even number) or 1 (for an odd number). If the number is even, we will add 1 to this number to change it to an odd number.

Python Code:

Random Even Number Functions


Your task consists of adapting the above three functions to create three additional functions, this time to generate random even numbers using all three methods/programming constructs: sequencing, selection and iteration.

Extension Task: Random Prime Number Function


For this more complex extension task, you will need to write a function called randomPrimeNumber() to generate a random prime number within a given range. This function will take two parameters: the lower and higher values of the range.

unlock-access

Solution...

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

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