More results...

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

Bracket Validator

bracketsThe aim of this Python Challenge is to write a script to validate an arithmetic expression by checking that it has a valid sequence of opening and closing brackets.

Let’s consider the following arithmetic expressions to decide whether they contain a valid or invalid combination of brackets:

Arithmetic Expression Valid/Invalid? Justification
(5+2)/3 Valid
(((5+2)/3)-1)*4 Valid
(5+2)*(3+4) Valid
(5+2 Invalid Missing closing bracket
(5+2)*)3+4( Invalid Invalid use of brackets
(5+2)/3)-1 Invalid Missing an opening bracket

Opening & Closing Brackets Count

In order to validate whether an expression is valid or not, we could count the number of opening brackets and the number of closing brackets and see if both numbers are the same. Though this would detect a lot of invalid expressions, not all invalid expressions would be detected. For instance, using this approach, the expression (5+2)*)3+4( would appear valid as it contains 2 opening brackets and 2 closing brackets.

Using a stack

A more effective approach is to parse the expression one character at a time and every time an opening bracket is met, the bracket is pushed into a stack. Every time a closing bracket is found, we pop the last opening bracket from the stack (if when a closing bracket is met, the stack is empty then the expression is invalid). Once all characters of the expression have been checked, the stack should be empty. If not the expression is invalid.

Here is the implementation of this approach in Python:

Using multiple types of brackets

More complex expressions may use different types of brackets such as square brackets [], curly brackets {} and parentheses (). We can adapt our script to validate an expression by making sure that when a closing bracket is found, the algorithm checks that it is of the same type as the last bracket that has been pushed into the stack.

Proportions and cross products

A proportion is simply a statement that two ratios are equal. The following are examples of proportions:

  • 1/4 = 25/100
  • 8/24 = 1/3
  • 40/60 = 2/3

Proportions are often use in Maths to simplify a fraction or to represent a fraction as a percentage.
percentage

In order two find out if two fractions are equal, we can use one of the following three methods:

  • Calculate and compare their decimal values: e.g. 25/100 = 0.25 and 1/4 = 0.25 so 25/100 = 1/4
  • Simplify both fractions: e.g. 75/100 = 3/4 and 18/24 = 3/4 so 75/100 = 18/24
  • Compare cross products: e.g. 3 x 6 = 2 x 9 so 2/6 = 3/9

Cross Products


You can compare two fractions to find out if they are equal or not if their cross products are equal:
cross-products

Python Challenge


Your aim is to write a Python program that will check if two fractions are equal or not using the cross products approach. The program will take 4 inputs: the numerator and denominator of both fractions.
It will then compare the cross products to decide and output if the two fractions are equal or not.

You will not to complete the following code:

Test Plan


Complete the following tests to check that your code is working as expected:

Test # Input Values Expected Output Actual Output
#1 Fraction #1: 4/6
Fraction #2: 20/30
These fractions are equal.
#2 Fraction #1: 4/6
Fraction #2: 20/40
These fractions are not equal.
#3 Fraction #1: 75/100
Fraction #2: 3/4
These fractions are equal.
#4 Fraction #1: 1/3
Fraction #2: 30/100
These fractions are not equal.
unlock-access

Solution...

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

Linked Lists

A linked-list is a dynamic data structure used in computer science. It consists of a collection of nodes where each node contains a piece of data (value) and a pointer (memory location) to the next node in the list.

The first node of the list is called the head, whereas the last node is the tail.
linked-list

The following tables represent how the above linked list is stored in memory:

Memory Address linked-list-nodeNode Value linked-list-pointerPointer
0 21 1
1 35 2
2 47 3
3 89 Null

The linked-list data structure is more flexible than the array data structure as it allows for efficient insertion or removal of elements from any position in the sequence.

Inserting a value in a linked list:

Let’s see how we can add the value 52 in the correct (sorted) position:
linked-list-before-insertion
linked-list-after-insertion
As you cans see on the table below, we have been able to add the value 52 to the linked list, in the desired position, without the need to move any other value in memory. The pointer of the previous node in the list has been updated accordingly.

Memory Address linked-list-nodeNode Value linked-list-pointerPointer
0 21 1
1 35 2
2 47 4
3 89 Null
4 52 3

Though the data does not appear to be sorted in memory, the use of pointers enables the linked-list to have its own sequence. This makes the process of inserting and removing values from a linked list far more efficient as it does not require other values to be moved around in memory (a fairly slow process when manipulating a large amount of data).

Removing a value from a linked list:

Let’s now remove value 35 from the list:
linked-list-deletion

Memory Address linked-list-nodeNode Value linked-list-pointerPointer
0 21 2
1 35 2
2 47 4
3 89 Null
4 52 3

Circular list

Imagine all the children in the “pass the parcel” game. The parcel is passed around the children and when the last child receives the parcel, they then pass it on back to the first child in the list.

A circular list is when the pointer of the tail node points towards the head node of the linked list.
circular-list

Memory Address linked-list-nodeNode Value linked-list-pointerPointer
0 21 1
1 35 2
2 47 3
3 89 0

Double linked list

A double linked list uses two pointers per node, one pointer pointing towards the next node in the list and one pointer pointing towards the previous node in the list. It makes it easier to “navigate through” the list in both directions!
double-linked-list

Memory Address linked-list-nodeNode Value linked-list-previous-pointerPrevious Node Pointer linked-list-pointerNext Node Pointer
0 21 Null 1
1 35 0 2
2 47 1 3
3 89 2 Null

Circular Double linked list

A Circular double linked list is when the tail node points back to the head node and vice versa:
circular-double-linked-list

Memory Address linked-list-nodeNode Value linked-list-previous-pointerPrevious Node Pointer linked-list-pointerNext Node Pointer
0 21 3 1
1 35 0 2
2 47 1 3
3 89 2 0

Other use of linked lists…

Linked-lists can be used to implement more abstract data types such as queues, stacks and binary trees.

XOR Encryption Algorithm

The XOR Encryption algorithm is a very effective yet easy to implement method of symmetric encryption. Due to its effectiveness and simplicity, the XOR Encryption is an extremely common component used in more complex encryption algorithms used nowadays.

The XOR encryption algorithm is an example of symmetric encryption where the same key is used to both encrypt and decrypt a message.

Symmetric Encryption: The same cryptographic key is used both to encrypt and decrypt messages.

Symmetric Encryption: The same cryptographic key is used both to encrypt and decrypt messages.

The XOR Encryption algorithm is based on applying an XOR mask using the plaintext and a key:

Reapplying the same XOR mask (using the same key) to the cipher text outputs the original plain text. The following truth table (based on the XOR truth table) demonstrates how the encryption process works.

P (Plain text) K (Key) C (Cipher)
=
P XOR K
K (Key) P (Plain Text)
=
C XOR K
0 0 0 0 0
1 0 1 0 1
0 1 1 1 0
1 1 0 1 1

The XOR encryption algorithm can be applied to any digital/binary information, included text based information encoded using the 8-bit ASCII code. In this case the encryption key can be expressed as a string of characters.

By itself, the XOR encryption can be very robust if:

  • It is based on a long key that will not repeat itself. (e.g. a key that contains as many bits/characters as the plaintext)
  • A new key is randomly generated for any new communication.
  • The key is kept secret by both the sender and the receiver.

When a large quantity of text is to be encrypted, a shorter repeating encryption key is used to match the length of the plain text. However re-using the same key over and over, or using a shorter repeating key results in a less secure method where the cipher text could be decrypted using a frequency analysis.
xor-encryption-keys

Python Code


In this Python code we are using the XOR bitwise operator (in Python: ^) to apply the XOR mask using the plain text and the key.

To improve readability, we are displaying the cipher text in different format: Ascii, Denary, Hexadecimal and Binary format.

Tagged with: ,

Eureka! (and King Hiero’s Crown)

Archimedes is one of the most famous physicist, mathematician, astronomer and inventor of the classical age.

Archimedes is one of the most famous physicist, mathematician, astronomer and inventor of the classical age.

Did you know?


Archimedes is one of the most famous physicist, mathematician, astronomer and inventor of the classical age: He lived in Syracuse on the island of Sicily in the third century B.C. Many of his inventions and theories are still being used today.

This Python challenge will be based on Archimedes’ most famous “Eureka!” moment: At the time, Hiero, The King of Syracuse (Sicily, Italy), had given his goldsmith some pure gold and asked him to make a crown out of this gold. On reception of the crown, Hiero suspected he had been cheated by the goldsmith. He believe the goldsmith had replaced some of the pure gold with the same weight of silver. However Hiero needed to be able to prove that his suspicion was correct and that the crown was not made of pure gold.

Knowing the weight/mass of the crown was not enough to confirm whether the crown was made of pure gold (as opposed to a mix of gold and silver). However if Archimedes knew that if he could accurately measure the volume of the crown, he could work out its density. (Density = mass / volume). He could then compare this density with the density of pure gold to see if they are the same. If not, this would be the proof that the crown is not just made of pure gold which would confirm Hiero’s suspicion. The issue was that, though it was easy at the time to precisely measure the mass of an object, there was no method for working out the exact volume of an irregular object (such as a crown!).

It’s while stepping into a bath that Archimedes noticed that the water level rose: he immediately deducted that the volume of water displaced must be equal to the volume of the part of his body he had submerged. He then realised that the volume of irregular objects could be measured with precision using this submersion approach. He is said to have been so eager to share his discovery that he leapt out of his bathtub and ran naked through the streets of Syracuse shouting Eureka! Eureka! (Greek for “I have it!”).

The volume of an object is equal to the volume of the water displaced when this object is submerged.

The volume of an object is equal to the volume of the water displaced when this object is submerged.

By applying this approach to the golden crown, Archimedes was able to get an accurate measure of the volume of the crown and could hence calculate the density of the crown which effectively turned out to be of a lesser density than pure gold. This confirmed Hiero’s suspicion that his goldsmith had stolen some of the pure gold he was given to make this crown!

Python Challenge


In this Python challenge we will use a program to help identify the density of an object and compare with the known density of different metals such as gold, silver, bronze, etc.

Our algorithm will:

  1. Ask the user to enter the mass of an object. (in Kg)
  2. Ask the user to enter the volume of an object. (in m3)
  3. Calculate and output the density of this object (mass/volume)
  4. Compare this density with the densities of different metals such as pure gold, silver and bronze and output the corresponding metal if there is a match.

Our algorithm will use the following data:

Metal Density
Aluminium Between 2400 kg/m3 and 2700 kg/m3
Bronze Between 8100 kg/m3 and 8300 kg/m3
Silver Between 10400 kg/m3 and 10600 kg/m3
Lead Between 11200 kg/m3 and 11400 kg/m3
Gold Between 17100 kg/m3 and 17500 kg/m3
Platinum Between 21000 kg/m3 and 21500 kg/m3

Your Challenge


Complete the code below and use your code to work out what the following four crowns are made of…

Test # Object Input Values Output
#1 crown-1 Mass:0.567kg
Volume: 54cm3 = 0.000054m3
#2 crown-2 Mass:1.213kg
Volume: 70cm3 = 0.00007m3
#3 crown-3 Mass:0.731kg
Volume: 65cm3 = 0.000065m3
#4 crown-4 Mass:0.585kg
Volume: 71cm3 = 0.000071m3

Python Code


You will need to complete the code provided below:

unlock-access

Solution...

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

Searching & Sorting Algorithms Practice

weather-chartThe searching and sorting algorithms are key algorithms that you will study in computer science. Most computer programs involve some searching and sorting features so these key algorithms are often used when coding various computer programs. Searching and sorting algorithms are also useful to develop your algorithmic thinking skills and your ability to compare and evaluate the effectiveness of an algorithm to perform a specific task.

You will find in this blog a range of activities on sorting and searching algorithms. This online task will help you demonstrate or practise your understanding of the key searching and sorting algorithms by applying these to a list of 10 randomly generated numerical values.

Practise your Searching & Sorting Algorithms online
Linear SearchBinary SearchInsertion SortBubble SortMerge SortQuick Sort
card-sort-linear-search
card-sort-binary-search
card-sort-insertion-sort
card-sort-bubble-sort
card-sort-merge-sort
card-sort-quick-sort
Tagged with:

Taboo Revision Game (A Level)

taboo-cardsCheck our version of the Taboo game focusing on A level computer science terminology. The objective of the game is for a player to have their partners guess the word on the player’s card without using the word itself or five additional words listed on the card. The player has a fixed amount of time (30 seconds, one minute or two minutes, to be agreed at the start of the game). They should use this time to get their partners to guess as many words as possible.

If the player passes a card or uses one of the taboo words, they lose one point. For every word that is correctly guessed by their partners, they score one point. The player is not allowed to use any forms of the word listed. When acronyms are used, the player is not allowed to use any of the words that the acronym stands for.

One the cards below, the words to be guessed appear at the top of the card (white font) whereas the taboo words are listed on the white section of the card (grey font).
A Level Computer Science RevisionOpen Taboo Game in New Window

The commuter’s puzzle

to-the-moon-and-backYuri lives in Oxford, UK and commutes by train to his work place in London every working day of the week (5 days a week).

One evening, Yuri spot the Moon through the train window and asked himself the following question:

“In how many years will I have travelled the equivalent distance of going to the Moon and back due to my daily commute?”

On a piece of paper Yuri has gathered some data needed to answer this question:

Description Value
Distance between Oxford and London: 60 miles
Distance between planet Earth and the Moon: 383,400km
Number of km in 1 mile: 1.609km
Number of working days per week: 5
Number of weeks in a year: 52

He has also drawn the following flowchart to help him find the answer. His intention was to then use some Python code to implement this flowchart and work out the answer to his question. This algorithm is a sequencing algorithm based on the following steps:

  1. Work out the total distance travelled over a year (in km).
  2. Work out the distance of a return journey to the Moon (in km).
  3. The number of years can be calculated by dividing the distance of a return journey to the Moon by the total distance travelled over a year.

sequencing-label
flowchart-to-the-moon-and-back

Python Code


You can use the above flowchart to complete the Python code for this sequencing algorithm.

unlock-access

Solution...

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

Mission Alpha-Centauri

Did you know that Alpha-Centauri is the second nearest star to planet Earth, the first one being the Sun. It is 4.2 light-years away from us!

When astronomers measure the distance of stars (from planet Earth) they do not use the kilometer (km) unit but instead they use the light-year unit. One light-year represents the distance that light travels in one year, at the speed of light (300,000 km/s).

stars-galaxy
The aim of this challenge is to convert the distance between planet Earth and Alpha-Centauri from light-years to km.

To do so we will use a sequencing algorithm based on the following steps:

  1. Calculate the number of seconds in a year,
  2. Multiply this number by the speed of light,
  3. Multiply this number by 4.2 (the distance of Alpha-Centauri from Earth in light-years).
  4. Output the result/ distance in km

sequencing-label

Flowchart


The flowchart of this sequencing algorithm is as follows:
alpha-centauri-flowchart

Python Code


You can now implement this sequencing algorithm using Python code:

Step 2: using Selection


Your next challenge is to let the user choose a star, and based on their choice, you will output the distance between the selected star and planet Earth, in km using the following data:

Star Distance from Earth (in light-years)
Alpha Centauri 4.24 light-years
Barnard’s Star 5.96 light-years
Luhman 16 6.59 light-years
WISE 0855-0714 7.2 light-years
Wolf 359 7.78 light-years

To do so you will use an if, elif and else statements to implement a selection construct.
selection-label

Step 3: using Iteration


Finally, using a while loop, you will keep asking the user to choose a star to repeat the above process with the user’s selection, until the user decides to quit the program. Using a while loop is an example of iteration!
iteration-label

Tagged with: , ,

2D Rotation Matrix

In this post, we will investigate how we can use the 2D rotation matrix to calculate the coordinates of a point when applying a 2D rotation of a set angle, Θ.
2D-Rotation

Here is the 2D rotation matrix:
2D-Rotation-Matrix

Which results in the following two equations where (x,y) are the cartesian coordinates of a point before applying the rotation, (x’,y’) are the cartesian coordinates of this point after applying the rotation and Θ is the angle of rotation
2D-Rotation-Coordinates

2D Rotation Demo


We have created a demo using the processing library to represent an X-Wing spacecraft (top-down view). The spacecraft is defined as a list of shapes, where each shape is a sublist of (x,y) coordinates (the vertices of the polygonal shape).

We are then applying the 2D rotation formulas to apply an angle of rotation (calculated based on the position of the mouse cursor on the canvas) and hence calculated the new coordinates of each vertices.

Finally, using the line() function of the processing library we the draw the spacecraft by plotting and joining all these vertices together.