More results...

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

Stacks and Queues in LMC

In this post we will investigate how to implement a queue and a stack data structure using low-level programming. We will use an upgraded version of Little Man Computer (LMC) that supports indirect addressing to to do.

Implementing a Queue in LMC


A queue is a FIFO data structure: First-In First-Out in other words, it is used to implement a first come first served approach. An item that is added (enqueue) at the end of a queue will be the last one to be accessed (dequeue).

queue-diagram

Two pointers are needed to implement a queue data structure: A front pointer which holds the memory address of the first item of the queue and a rear pointer which holds the memory address of the last item of the queue.

When implementing a Queue data structure we need to implement two algorithms/functions to enqueue a new value at the end of the queue and to dequeue a value from the front of the queue.

Algorithm to enqueue a value to a queue:

FUNCTION ENQUEUE(value):
     If queue IS NOT FULL:
            rearPointer = rearPointer + 1
            queue[rearPointer] = value

Algorithm to dequeue a value from a queue:

FUNCTION DEQUEUE():
     If queue IS NOT EMPTY:
            value = queue[frontPointer]
            frontPointer = frontPointer + 1
            RETURN value

Low Level Implementation of a queue using LMC:

menu    INP
        SUB one
        BRZ enqueue 
        SUB one 
        BRZ dequeue
        BRA exit
	
exit    HLT
 
enqueue LDA max
        SUB rear
        BRZ full
        INP
        STA @rear
        LDA rear
        ADD one
        STA rear
        BRA menu

full    LDA error1
        OUT
        BRA menu

dequeue LDA front
        SUB rear
        BRZ empty
        LDA @front
        OUT
        LDA front
        ADD one
        STA front
        BRA menu

empty   LDA error2
        OUT
        BRA menu

front   DAT 50
rear    DAT 50 
one     DAT 1 
max     DAT 100 
error1  DAT -1  
error2  DAT -2

The above algorithm works as follows:

  • The user needs to input one of the following three menu options:
    • 1: To enqueue a new value,
    • 2: To dequeue a value,
    • Any other value: To exit the program.
  • If the user opts for option 1, they will then need to input the value to enqueue. They will then be redirected to the start of the program to input their next option from the menu. If the queue is full, the program will output the error code -1. The queue will be stored in memory starting at memory location 50. The queue will be full once it reaches memory location 99.
  • If the user opts for option 2, a value will be removed from the queue and displayed as an output. They will then be redirected to the start of the program to input their next option from the menu. If the queue is empty, the program will output the error code -2.
  • The program will stop if the user selects a value different from 1 or 2 from the menu.

Direct vs indirect addressing:
The LMC language was initially implemented to only support direct addressing: Each operand is a memory location of where the data to be used is stored. However to access the value stored at the front (dequeue) or rear (enqueue) memory locations of the queue it is necessary to use indirect addressing. The above code will hence only work with an LMC simulator that supports indirect addressing. In the code above the @ sign is used to indicate when indirect addressing is used. The following page gives more explanations of the main memory address modes used in low-level languages.

You can try code provided above in our LMC simulator as it does support indirect addressing:
LMC SimulatorOpen in New Window

Test Plan:

Test # Input Values Expected Output Pass/Fail?
#1 1,10 – 1,11 – 1,12 – 2 – 2 – 2 – 2 – 3 LMC-Queue-Test-2
#2 1,1 – 1,2 – 1,3 – 2 – 1,4 – 2 – 1,5 – 2 – 3 LMC-Queue-Test-1

Implementing a Stack in LMC


A stack is a FILO data structure: First-In Last-Out. Imagine a stack of books piled up on a table. When you add (push) a book on top of the pile, it will be the first book that you will then take (pop) from the pile (stack).

stack-diagram

Only one pointer is needed to implement a stack data structure: An End of Stack pointer which holds the memory address of the last item of the stack.

When implementing a Stack data structure we need to implement two algorithms/functions to push a new value at the end of the stack and to pop a value from the end of the stack.

Algorithm to push a value to a stack:

FUNCTION PUSH(value):
     If stack IS NOT FULL:
            stackPointer = stackPointer + 1
            stack[stackPointer] = value

Algorithm to pop a value from a stack:

FUNCTION POP():
     If stack IS NOT EMPTY:
            value = stack[stackPointer]
            stackPointer = stackPointer - 1
            RETURN value

Your Challenge:
Your challenge is to adapt the code given to implement a queue in order to implement a stack instead. You will need to apply the right terminology (push and pop instead of enqueue and dequeue) and apply the above two algorithms in LMC.

Tagged with:

Algebraic Pyramid Challenge

algebraic-pyramidFor the purpose of this challenge we will use algebraic pyramids pointing downwards (or upside down pyramids!).

The idea of this mathematical puzzle is to fill in all the bricks of a pyramid based on the following rule:

  • To work out the value of a brick, add the values of the two adjacent bricks above it.

algebraic-pyramid-rule

Python Challenge #1: Fix sized pyramids


This Python challenge will consist of writing a procedure that will take a list of values as a parameter, and will as a result generate and output an upside down pyramid where the top layer of the pyramid will contain all the values from the given list.

To simplify this problem, we will first assume that the list of number will always contains exactly 4 values.
For example:
algebraic-pyramid-list

The output of our procedure should be as follows:
algebraic-pyramid

Challenge #1: Python Code:


You will need to complete the following python code to work out and print all the layers of the pyramid.

Challenge #1: Test Plan


Check that your code is working using the following list of 4 values.

Test # List Expected Output Pass/Fail?
#1 [4,6,8,2] algebraic-pyramid-test-2
#2 [30,12,10,5] algebraic-pyramid-test-1
#3 [3,6,9,12] algebraic-pyramid-test-3

Challenge #2: Using lists of different sizes


The second challenge consists of adapting the code from challenge 1 to make sure that it works for any list (of any length) of values.

Challenge #2: Test Plan

Test # List Expected Output Pass/Fail?
#1 [3,6,9] algebraic-pyramid-test-3-layers
#2 [30,12,10,5] algebraic-pyramid-test-1
#3 [1,2,3,4,5,6] algebraic-pyramid-test-6-layers
Tagged with:

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: