More results...

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

Square Root Estimation Algorithms

square-rootCalculating the square value of a number is a very straightforward
process which consists of multiplying this number by itself. For instance:

152 = 15 x 15 = 225

The reverse operation which consists of calculating the square root of a number is not so easy without using the square root function of a calculator. In this blog post we will investigate how to accurately calculate the square root of a number using Python and we will then implement and compare two methods that were used a few centuries ago to estimate the square root value of any given number:

  • The Babylonian Method,
  • The Bakhshali Method.

Exponentiation

High level programming languages such as Python have an arithmetic operator to raise a number to the power of an exponent.

In pseudocode the exponentiation operator is the ^ operator.
For instance: 32 appears as 3^2 when using pseudocode.

In Python, the exponentiation operator is **. e.g.:

# 5 to the power of 2 is 25
square = 5 ** 2
# 5 to the power of 3 is 125
cube = 5 ** 3

Square Root = To the power of half

We can easily calculate the square root of a number in a computer program using the exponentiation operator knowing that:

√x = x½ = x0.5

So in Python:

# Square root of 25 is...
sqrt = 25 ** 0.5

The Babylonian method

Procedures for calculating/estimating square roots have been known since at least the period of ancient Babylon in the 17th century BCE. Heron’s method (aka Babylonian method) from first century Egypt was the first ascertainable algorithm for computing square root.

This approach is based on estimating the limit of the following convergent sequence:
babylonian-square-root

To implement the Babylonian method of estimating a square root we will use the following algorithm:
square-root-flowchart

Python Code

Use the above flowchart to complete the code below:

The Bakhshali method

This method for finding an approximation to a square root was described in an ancient Indian mathematical manuscript called the Bakhshali manuscript. It uses a similare approach the Babylonian method using a different convergent series as described below:

bakhshali-square-root

Your task is to adapt your Python script to implement the Bakhshali method and compare how both series perform to estimate a square root value using a fixed number of iterations.

unlock-access

Solution...

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

Multimedia Library (OOP Concepts)

multimedia-libraryIn this blog post, we will write a computer program to create and maintain a multimedia library of books, CDs and DVDs. The aim of this programming task is to demonstrate some key Object-Oriented Programming concepts such as:

  • Creating Classes and Objects,
  • Using Derived Classes (implementing Inheritance),
  • Using an Abstract class,
  • Implementing over-riding Polymorphism,
  • Implementing over-loading Polymorphism.

Class Diagram

This project will be based on the following class diagram:
multimedia-library-class-diagram

The Library class will be used to maintain a list of items (Books, DVDs, CDs). It will have a range of methods to:

  • Add a new item to the list of items,
  • Remove an item from the list of items,
  • View the full list of items,
  • Reset/Empty the list of items,
  • Find out the number if items in the library.
  • Find out if the library is empty.

Abstract Class

The Item class is an abstract class: It will not be used to instantiate objects directly from this class. Instead, objects will be instantiated from the three derived classes Book, CD and DVD.

Inheritance

This class diagram clearly shows the inheritance relationship between the Item class and the Book, CD and DVD classes:

  • The Item class is the parent class (also called master class or super class)
  • The Book class, CD class and DVD class are the derived classes (also called sub classes or child classes).

When a class such as the Book class inherit from a parent class (Item class), it inherits all the properties and methods from the parent class. Hence a book will inherit the title and the description properties as well as the viewDescription() method from the Item class.

Additional properties and methods can be added to a derived class. For instance the Book class as its own specific properties: author and isbn.

Over-Riding Polymorphism

The viewDescritpion() method is an example of over-riding polymorphism: It has been defined in the parent Item class as an abstract method. It is then implemented differently in the derived classes Book, CD and DVD. You can check the Python code in the trinket below to see the three different implementations of the viewDescription() method in the Book, CD and DVD classes.

Over-Loading Polymorphism

We did not implement over-loading polymorphism in this example as it is not directly supported in Python. Over-loading polymorphism is used when the same method is implemented several times within a class, each time accepting a different set of parameters (either a different number of parameters, or using parameters of different data types).

For instance, we could implement over-loading polymorphism to the addItem() method of the Library class as follows:

def addItem(self, item): #the item parameter is an object (e.g. Book, CD or DVD)#
   self.items.append(item)

def addItem(self, title, description, author, isbn):
   book = Book(title, desription, author, isbn)
   self.items.append(book)

def addItem(self, title, description, artist, genre, numberOfTracks):
   cd = CD(title, desription, artist, genre, numberOfTracks)
   self.items.append(cd)

def addItem(self, title, description, director, certificate):
   dvd = DVD(title, desription, director, certificate)
   self.items.append(dvd)

You can read this article to find out how to implement overloading polymorphism in Python using the multipledispatch library.

Python Code

Here is the Python code for our multimedia library project:

Tagged with:

MP3 Playlist Class

iPodThe aim of this challenge is to implement a Class in Python to maintain an MP3 Playlist. This class could be used when developing the software for a music App on a smartphone or an mp3 player.

This MP3 playlist will be stored as a queue of MP3 tracks. When new tracks are being added to the playlist, they are enqueued at the end of the playlist. The key features that we will implement within this class are the ability to:

    Load a playlist from a text file,
    Display all the tracks from the playlist,
    Enqueue an MP3 to the playlist,
    Remove an MP3 from the playlist,
    Save a playlist on a text file,
    Shuffle all the songs in the playlist,
    Count the number of tracks in the playlist,
    Calculate the total duration of the playlist,
    Empty/Reset the playlist,
    Check if the playlist is empty.

Here is the class diagram for this project:
mp3-playlist-class

Python Code

We have started the code used to load a mp3 playlist from a text file.
Your task is to complete this code to implement all the methods mentioned above.

Solution (Step by step)

load() & save()enqueue()remove()getNumberOfTracks()getTotalDuration()shuffle()reset()isEmpty()
The load() and save() methods are used to load a playlist from a CSV file and save it on the CSV file. The save method() will overwrite the playlist if it already exists or create a new file if the file does not exists.

Here is the code to add to the Playlist class:

def load(self):
    self.tracks = []
    print("Loading tracks from CSV file.")
    file = open(self.filename,"r")
    for line in file:
      fields = line.split(";")
      track = Track(fields[0],fields[1],int(fields[2]))
      self.tracks.append(track)    
    file.close()
    
def save(self):
    print("Saving your playlist...")
    file = open(self.filename,"w")
    for track in self.tracks:
      file.write(track.title + ";" + track.artist + ";" + str(track.duration)+ ";")
    file.close()
    print("Playlist saved!")

In the main program we can test our load() and save() methods using the following code:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()
myPlaylist.view()

#Add or remove tracks or shuffle the playlist... using the enqueue(), remove() and shuffle() methods.

myPlaylist.save()
The enqueue() method from the Playlist class is used to append a track at the end of the tracks list:

def enqueue(self, track):
    self.tracks.append(track)

You can test this code as follows:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

newTrack = Track("Wonderwall","Oasis",245)
myPlaylist.enqueue(newTrack)
myPlaylist.view()

myPlaylist.save()
The remove() method from the Playlist class is used to remove a track from the track list:

def removeTrack(self, track):
    self.tracks.remove(track)

You can test this code as follows:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

myPlaylist.view()
myPlaylist.removeTrack(myPlaylist.tracks[2]) #This will remove the third track from the playlist!
myPlaylist.view()
This method will return the length of the tracks list.

def getNumberOfTracks(self):
    return len(self.tracks)

To test this method:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

numberOfTracks = myPlaylist.getNumberOfTracks()
print("This playlist has " + str(numberOfTracks) + " tracks!")
To calculate the total duration of a playlist we need to add the duration of each of its tracks.

def getTotalDuration(self):
    duration = 0
    for track in self.tracks:
      duration += track.duration
    return duration

To test this method:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

duration = myPlaylist.getTotalDuration()
print("This playlist lasts " + str(duration) + " seconds!")
The shuffle method just needs to shuffle the list of tracks using the shuffle() function from the random library.
We will hence need to import the random library by adding the following line at the top of the playlist.py file:

import random

Then we will add the following method to the Playlist class:

def shuffle(self):
  random.shuffle(self.tracks)

In the main program we can test our shuffle method using the following code:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

myPlaylist.shuffle()
myPlaylist.view()
To reset a playlist we just need to reset its tracks list to an empty list.

def reset(self):
  self.tracks = []

In the main program we can test our reset method using the following code:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

myPlaylist.reset()
myPlaylist.view()
To check is a playlist is empty we can check if the length of its tracks list is equal to 0.

def isEmpty(self):
  return len(self.tracks)==0

In the main program we can test our reset method using the following code:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

if myPlaylist.isEmpty():
   print("Your playlist is empty.")

myPlaylist.reset()

if myPlaylist.isEmpty():
   print("Your playlist is empty.")

myPlaylist.view()
Tagged with:

Shopping Basket Class

shopping-basketOne of the key features of any e-commerce website is the shopping basket. It is used to let the end-users add products to their basket before proceeding to checkout.

In this Python challenge we will create a Shopping Basket class to implement the different functionalities (behaviours) such as:

    Adding an item to the shopping basket,
    Removing an item from the shopping basket,
    Updating the desired quantity of an item from the shopping basket,
    Viewing/listing the content of the shopping basket,
    Calculating the total cost of the shopping basket,
    Emptying/Resetting the shopping basket,
    Checking if the shopping basket is empty.

To do so we will create the following two classes:
shopping-basket-class

The items property of the Shopping Basket class will be a dictionary of items:quantity pairs. (The items are the keys, for each key, the quantity in the basket is the value)

Python Code

Your task

Add a new “Stock Level” property to the item class.

Update the addItem(), removeItem(), updateItem() and reset() methods of the Shopping Basket class to check the availability of the item in stock before adding/changing the desired quantity, and by updating the Stock Level property of the item class accordingly when items are added/removed from the shopping basket.

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 Library Challenges

In this blog post we will experiment using some of the key functions from the random library. Many Python games will involve some degree of “randomness” for the game to be more realistic and unpredictable. Flipping a coin, throwing a dice, shuffling a deck of cards, spawning a sprite at a random location, generating a random password are all actions that can be implemented in Python fairly easily using the random library.

So let’s first investigate the most useful functions from this library to find out how to:

  • Generate a random number/integer,
  • Generate a random letter from the alphabet,
  • Select a random value from a list,
  • Identify a random index/location from a list,
  • Shuffle the values from a list.

We will then apply these techniques to solve a set of mini challenges to generate the following random values:
random-library-tasks

Using the random libraryPython IDEPython Challenges

Generating a random integer:

To generate a random number between two values (e.g. between 1 and 10), you will need to use the random.randint() function:

import random
number = random.randint(1,10)
print(number)

Generating a random letter from the alphabet: (Using the ASCII code)

To generate a random letter from the alphabet we can use the ASCII code where the ASCII code for letter “A” is 65 and the ASCII code for letter “Z” is 90. To do so we will generate a random number between 65 and 90 to then retrieve the matching ASCCI character using the chr() function.

import random
ascii = random.randint(65,90)
letter = chr(ascii)
print(letter)

Generating a random letter from the alphabet: (Using the random.choice() function)

An alternative approach used to generate a random letter from the alphabet is to randomly select a character from a string using the random.choice() function.

import random
letter = random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
print(letter)

Selecting a random value from a list: (using a random index)

We can randomly select a value from a list by first generating a random number between 0 and the length of the list -1. We can then use this rnadomlygenerated index to access the value from the list at the given position/index.

import random
weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
index = random.randint(0,len(weekdays)-1)
day = weekdays[index]
print(day)

Selecting a random value from a list: (using the random.choice() function)

The random.choice() function can also be used to randomly pick a value from a list

import random
weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
day = random.choice(weekdays)
print(day)

Shuffling list:

The random.shuffle() function is used to shuffle all the values from a list.

import random
weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
random.shuffle(weekdays)
print(weekdays)

Adapt the code provided to complete the following challenges:

Challenge #1: Generating a random IP address:

random-ip-address
An IP address consists of 4 numbers between 0 and 255 separated by a dot. Your task is to write a Python script that generates and outputs a valid random IP address.

Challenge #2: Flipping a coin:

random-head-or-tails
Your task is to write a Python script that randomly outputs “Heads” or “Tails”.

Challenge #3: Throwing a dice:

random-throw-dice
Your task is to write a Python script to throw a dice by randomly generating a value between 1 and 6.

Challenge #4: Generating a random phone number:

random-phone-number
Your task is to write a Python script to generates a random phone number consisting of 11 digits.

Challenge #5: Generating a random postcode:

random-postcode
Your task is to write a Python script to generates a random UK postcode in the format: LetterLetterNumber_NumberLetterLetter.

Challenge #6: Generating a random date:

random-date
Your task is to write a Python script to generates a random date in the format: DD/MM/YYYY.

Challenge #7: Generating a randomly pick a playing card:

random-playing-card
Your task is to write a Python script to randomly pick and output a card from a deck of 52 playing cards. The program should output the suit and value of the card (e.g. 7 of hearts, Queen of clubs, etc…).

Challenge #8: Generating a random password:

random-password
Your task is to write a Python script to randomly generate a strong password mixing lowercase, uppercase, numbers and punctuation signs in any order.
You can check this post for some extra help on this challenge.

Challenge #9: Generating 6 random lottery numbers:

random-lottery-numbers
Your task is to write a Python script to randomly generates and outputs 6 unique random numbers between 1 and 50.
You can check this post for some extra help on this challenge.

unlock-access

Solution...

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

DOS Emulator using Python

In the 1980’s, when IBM introduced the IBM PC which was built with the Intel 8088 microprocessor, they needed an operating system. They approached Microsoft who provided IBM with the “Microsoft Disk Operating System”: MS-DOS.

A Disk Operating System is operated via a command prompt. The user can interact by typing key commands to maintain and operate their computer. One of the key functionality of a DOS operating system is the ability to navigate through the files and folders structure and create, rename, move or delete files and folders.

ms-dos-prompt

Try it yourself, by accessing this online DOS emulator.

In this blog post we will create a “DOS emulator” but only focusing on the navigation and maintenance of the files and folders structure. We will not implement other functionalities of a DOS.

Files & Folders Tree Structure

On a computer system, files and folders are organised using a Tree structure. For instance, let’s consider the following folder structure:
files-folders-structure

In MS-DOS, the main commands to navigate through and maintain a folder structure are:

Command Description
DIR To list the content of a directory/folder.
CD To change directory/folder. This can be used to access a subfolder or a parent folder (e.g. cd ..)
MKDIR To make a new sub-directory/folder.
DEL To delete a file or a directory/folder. This would delete the content (subfolders and files of the directory)
MOV To move a folder or a file from one folder to another.
RENAME To rename a folder or a file.

Class Diagram

We will use a File class and a Folder class to implement this tree structure:
file-folder-classes

Python Code

We have started the code for you and implemented the CD, DIR, MKDIR, DELETE and RENAME instructions as well as a HELP and a CLS (clear screen) instruction. Your task is to complete this code to create the MOVE instruction and apply it to the Folder class to let the user move a file or folder within a subfolder or the parent folder. For instance to move a file to the parent folder, the user would type the following instruction:
MOVE sea.jpg ..
Or to move a file into a subfolder called “landscapes”:
MOVE sea.jpg landscapes

4-bit counter using D-Type flip-flop circuits

In this blog post we will design an electronic circuit using logics gates (combined into D-Type flip-flop circuits) to create a 4-bit binary counter. This approach will help us understand how a program counter may be designed within the CPU and automatically incremented for each tick of the clock cycle.

D-Type Flip-Flop Circuits?


A D-Type Flip-Flop circuit is built using four NAND logic gates connected as follows:
D-Type-Flip-Flop-Logic-Gates

We represent a D-Type Flip-Flop Circuit as follows. You can change the input values D and E by clicking on the corresponding buttons below to see the impact on the outputs Q and Q.




D-Type-Flip-Flop-Circuit



A D-Type Flip-Flop Circuit can be used to store 1 bit of information. It has two input pins (Called D (Data) and E (Enabler) and two output pins (Q and Q = NOT Q).

You can read more about how Random Memory is designed using D-Type flip flop circuits.

The truth table of a D-Type Flip-Flop circuit is as follows:
D-Type-Flip-Flop-Truth-Table

When the enabler input E is set to 1, the output Q can be set to the Data input D.
When the enabler input E is set to 0, the output Q cannot be changed. It remains as its previous value. In other word it retains its value. This is why this circuit is used to create memory cells (e.g in the RAM).

You can test this circuit online by clicking on the picture below:

Frequency Division

Another use of a D-Type flip-flop circuit is to perform a frequency division of a signal. For this type of circuit, we will need to use a slight variation to our D-Type Flip Flop by using an edge triggered D-type flip flop. The difference being that the output Q and Q can only change state with the transition of the clock pulse, which means when the Enabler is changing state from 0 to 1. After that, when the enabler is set to 1, the outputs Q and Q remain the same even when the data input D changes.

You can test this circuit online by clicking on the picture below:

By creating a feedback loop (connecting the output Q to the Data pin, D) and applying a regular clock signal to the Enabler pin (E), the resulting signal (pin Q) has the frequency of the input signal divided by two.
D-Type-Flip-Flops-feedback-loop
This diagram represents both the input and output signals when a feedback loop is applied to a D-Type flip-flop circuit:
D-Type-Flip-Flops-frequency-division
You can test this frequency divider circuit by clicking on the picture below:

Designing a 4-bit binary counter

By applying the same circuit in series we can then divide the frequency by 2, 4 and 8. The original signal (clock) and the 3 resulting signals will then produce the desired counting effect:
4-bit-counter-signals

You can test this circuit with our logic gates circuit simulator by clicking on the picture below:

And here is the full circuit using Logic.ly:
4-bit-counter-d-type-flip-flop

Tagged with:

Solving a Murder Mystery using Prolog

murder-mystery-cluedo
In the middle of last winter, eight guests were invited to a luxurious retreat at the Duke of York Grand Hotel. On the last day of their three-day getaway, the guests were free to vacate to their own occupations. Mrs White and Reverend Green did some “gardening” walking alongside the water fountains, Colonel Mustard and Professor Plum played golf (alone though, purposefully avoiding each other). The other guests spent their days either in their rooms or in the lounge, by the log fire. Later on in the afternoon, all the guests were indoors and Colonel Mustard was seen playing cards with Reverend Green and Mrs Peacock.

As the guests were called for dinner, they soon realised that Dr Black was missing. He was later found lying down on the floor of his bedroom. Dr Black had been shot dead using an old fashion revolver. Except from a few muddy footprints at the entrance of his bedroom, there was no other evidence left by the murderer.

Here is the list of all the guests for the weekend and the rooms they were staying in. Note that the hotel consists of twin bedrooms accommodating two guests per room. We also know that three of the guests (Reverend Green, Colonel Mustard and Madame Rose) own a revolver that they brought with them and kept in their room.

murder-mystery-clues

– Click on the picture to zoom in/enlarge –

Prolog?

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

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

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

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

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

Knowledge Base (Facts & Rules)

Let’s see how a detective with some good computer science skills would solve this murder mystery. Their first step would be to write all the facts about the case using the Prolog syntax:

/* Facts */
man(dr_black).
man(reverend_green).
man(colonel_mustard).
man(professor_plum).

woman(mrs_peacock).
woman(madame_rose).
woman(miss_scarlett).
woman(mrs_white).

victim(dr_black).

playing_cards(colonel_mustard).
playing_cards(reverend_green).
playing_cards(mrs_peacock).

gardening(mrs_white).
gardening(reverend_green).

played_golf(professor_plum).
played_golf(colonel_mustard).

smoker(miss_scarlett).
smoker(colonel_mustard).
smoker(mrs_white).
smoker(dr_black).
smoker(mrs_peacock).

room(room_21).
room(room_22).
room(room_23).
room(room_24).
room(room_25).

stay_in(dr_black,room_22).
stay_in(reverend_green,room_24).
stay_in(miss_scarlett,room_21).
stay_in(colonel_mustard,room_24).
stay_in(professor_plum,room_22).
stay_in(mrs_peacock,room_23).
stay_in(madame_rose,room_21).
stay_in(mrs_white,room_23).

owns_revolver(reverend_green).
owns_revolver(colonel_mustard).
owns_revolver(madame_rose).

Then our detective would write some rules and apply them to these facts.

A suspect is either a man or a woman who is not the victim!

#Rule #1:

This is how this rule would be implemented in Prolog:

suspect(X):- man(X), \+victim(X).
suspect(X):- woman(X), \+victim(X).

Any suspect who was seen playing cards at the time of the crime has a valid alibi!

#Rule #2:

This is how this rule would be implemented in Prolog:

has_alibi(X):- suspect(X), playing_cards(X).

Anyone who did some gardening, played golf or is a smoker has been outside at least once throughout the day.

#Rule #3:

This is how this rule would be implemented in Prolog:

went_outside(X):- gardening(X).
went_outside(X):- smoker(X).
went_outside(X):- played_golf(X).

The rooms of the hotel are twin rooms that can accomomdate two guests. Two guests share the same room if they both are booked in the same room.

#Rule #4:

This is how this rule would be implemented in Prolog:

share_room(X,Y):- room(R), stay_in(X,R), stay_in(Y,R), X \= Y.

Anyone who owns a revolver or share a room with another guest who owns a revolver, had access to a revolver!

#Rule #5:

This is how this rule would be implemented in Prolog:

revolver_access(X):- owns_revolver(X).
revolver_access(X):- share_room(X,Y), owns_revolver(Y).

Solving this murder case!

Step 1: Can you use all the above facts & rules to work out the actual murderer?

Step 2: Can you write one final rule needed to solve this murder mystery in just one query?

To find our culprit we need to find a suspect, who went outside (we found some muddy footprints on the floor next to Dr Black’s body), who has no alibi and who had access to a revolver!

You can access the detective’s knowledge base:
https://swish.swi-prolog.org/p/murder-mystery.pl
Murder Mystery CodeOpen in New Window

Solution:

This is how our final rule would be implemented in Prolog:
View Solution!

Going a step further…

Now that you have solved this task, update the case by adding additional characters/suspects and additional clues. Make sure that at the end, the murderer of your case can still be found in just one query.

As additional suspects you could add some additional guests:

  • Mr Peach staying in room 25
  • Dr Orchid staying in room 25

Decide whether they went outside or not, whether they own a revolver or not, whether they were seen at the table playing card games or not! You can also add new indoors or outdoors activities.

You may also consider adding hotel staff members e.g.:

  • A barman,
  • A receptionist.

Staff members would have access to all the rooms!

Tagged with:

OOP Programming: Classes & Objects

OOP-Class-ObjectIn this blog post we will investigate how to create some basic classes and objects that could be used in a range of programming projects.

Classes and Objects are the building blocks of Object-Oriented programs. You can find out about more about the key concepts of Object-Oriented Programming (OOP).

A class is a template or blueprint from which objects will be instantiated. It’s like the mould from which objects can be created/instantiated from. A class represents a real life concept such as a person, an animal, a car, a house or a football.

A class consists of a collection of states (a.k.a. attributes or properties) and behaviours (a.k.a. methods).

An object is an instance of a class. The attributes of an object as stored using variables for storing data and the behaviour/methods of an object are implemented as functions or procedures and can be used to perform operations on the data.

Most classes have one method called a constructor. It is a function that is automatically called when an object is created/instantiated from a class. It is mainly used to initialise the default values for each attribute/variable of the object. In Python the constructor of a class is the __init__() function.

Dice ClassPadlock ClassDeck of cardsCoin Class
Our first class will be used to create basic game of dice. The Dice class will have two properties: numberOfSides and value and one method throw() that will update the dice value by generating a random number between 1 and numberOfSides (e.g. between 1 and 6 for a standard 6-side dice).
Dice-Class

Our second class is used to create a padlock with a four digit key. The Padlock class has an unlock() method used to test a combination to try to unlock the padlock.

The key of the padlock is stored in a private property: __key (In Python the “__” prefix is used to indicate a private property or method.) The key can still be accessed from outside the class using the two public methods getKey() and setKey(). This is an example of encapsulation.
Padlock-Class

To create a deck of cards we will create two classes as follows:
Card-and-Deck-Class

In order to create a game of Head or Tail we will create a Coin Class using two properties: faceUp (which will be either Head or Tail) and value of the coin (in pence) and one method to flip the coin.
coin-class
We will then create a game with ten rounds and two players. For each round, a coin will be created using a random value (1p, 2p, 5p, 10p, 20p, 50p, £1 or 2£). After flipping the coin, if the visible face is “Head”, player 1 wins the value of the coin otherwise it’s given to player 2.

Programming Challenge

Use the two classes Card and Deck (see above) to implement the card game “War” between two players using the following rules:

  • The deck of card is evenly divided among two players.
  • Battle: In unison, both players reveals the top card of their deck and the player with the higher card takes both of the cards played and add them to the bottom of their deck.
  • Rank: Aces are high, and suits are ignored.
  • War: A war occurs when the two cards played are of equal value. Both players place the next card of their pile face down and then another card face-up. The owner of the higher face-up card wins the war and wins all the cards on the table. If the face-up cards are once again of equal value then the battle repeats with another set of face-down/up cards. This repeats until one player’s face-up card is higher than their opponent’s.
  • Game Over: The objective of the game is to win all of the cards. The first player to run out of cards in their deck looses the war!
Tagged with: ,

Bubble Sort Algorithm in LMC

The aim of this challenge is to implement a Bubble sort algorithm on a list of 10 values using LMC.
We will be using our online LMC simulator to test our code
online LMC simulator:
LMC SimulatorOpen in New Window

LMC code using hardcoded valuesLMC code using input values
To simplify the testing process (and nto having to input 10 values each time we want to run/test the code, we have created a version of our Bubble sort algorithm where the 10 values are hardcoded in the code itself. You can change these values (v1 to v10) in the code from line 70 to 79.

init   LDA v0
       STA 90
       LDA v1
       STA 91
       LDA v2
       STA 92
       LDA v3
       STA 93
       LDA v4
       STA 94
       LDA v5
       STA 95
       LDA v6
       STA 96
       LDA v7
       STA 97
       LDA v8
       STA 98
       LDA v9
       STA 99

loop   LDA true
       STA sorted
       LDA first
       STA pos
       ADD one
       STA next
step   LDA @pos
       SUB @next
       BRZ pass
       BRP swap

pass   LDA pos
       ADD one
       STA pos
       LDA next
       ADD one
       STA next
       LDA pos
       SUB last
       BRZ repeat
       BRA step
   
swap   LDA @next
       STA temp
       LDA @pos
       STA @next
       LDA temp
       STA @pos
       LDA false
       STA sorted
       BRA pass

repeat LDA sorted
       SUB true
       BRZ exit
       BRA loop

exit   OUT
       HLT

pos    DAT
next   DAT 
temp   DAT
sorted DAT 0
true   DAT 1
false  DAT 0
one    DAT 1
first  DAT 90
last   DAT 99
v0     DAT 32
v1     DAT 7
v2     DAT 19
v3     DAT 75
v4     DAT 21
v5     DAT 14    
v6     DAT 95    
v7     DAT 35    
v8     DAT 61    
v9     DAT 50   
This version of the code will start by asking the user to enter 10 different numerical values that the code will then sort.

init   INP
       STA 90
       INP
       STA 91
       INP
       STA 92
       INP
       STA 93
       INP
       STA 94
       INP
       STA 95
       INP
       STA 96
       INP
       STA 97
       INP
       STA 98
       INP
       STA 99

loop   LDA true
       STA sorted
       LDA first
       STA pos
       ADD one
       STA next
step   LDA @pos
       SUB @next
       BRZ pass
       BRP swap

pass   LDA pos
       ADD one
       STA pos
       LDA next
       ADD one
       STA next
       LDA pos
       SUB last
       BRZ repeat
       BRA step
   
swap   LDA @next
       STA temp
       LDA @pos
       STA @next
       LDA temp
       STA @pos
       LDA false
       STA sorted
       BRA pass

repeat LDA sorted
       SUB true
       BRZ exit
       BRA loop

exit   OUT
       HLT

pos    DAT
next   DAT 
temp   DAT
sorted DAT 0
true   DAT 1
false  DAT 0
one    DAT 1
first  DAT 90
last   DAT 99

Executing the Code

We will be using our online LMC simulator to test our code
online LMC simulator:
LMC SimulatorOpen in New Window

Before testing this code in the online LMC simulator, we recommend increasing the clock speed:
LMC-clock-speed-max
We also recommend turning off the log file:
LMC-log-file-off
This will significantly reduce the execution time. With the data given, it will still take 831 FDE cycles to sort all 10 numbers:
LMC-number-of-FDE-cycles
LMC-sorted-list

Code Review

Let’s review how this code was constructed:

InitialisationBubble Sort
When running this code using the LMC simulator, you will notice that the first action performed by this code is to store the 10 given values in the RAM using locations 90 to 99:

bubble-sort-lmc-memory

This is done at the very start of the code in the init block:

init   LDA v0
       STA 90
       LDA v1
       STA 91
       LDA v2
       STA 92
       LDA v3
       STA 93
       LDA v4
       STA 94
       LDA v5
       STA 95
       LDA v6
       STA 96
       LDA v7
       STA 97
       LDA v8
       STA 98
       LDA v9
       STA 99

This code is using the 10 labels v1 to v9 declared at the end of the code from line 70:

v0     DAT 32
v1     DAT 7
v2     DAT 19
v3     DAT 75
v4     DAT 21
v5     DAT 14    
v6     DAT 95    
v7     DAT 35    
v8     DAT 61    
v9     DAT 50   
For each iteration of the Bubble sort algorithm we set a “sorted” flag to true.

loop   LDA true
       STA sorted

This flag will be overwritten if when scanning through the list a swap is made. If after checking all values of the list, the “sorted” flag is still equal to true, in this case we can deduct that the list if fully sorted and hence stop iterating.


We then reset the two pointers “pos” and “next” to first two memory locations of the list (memory location 90 (first) and 91 (first ADD one).

       LDA first
       STA pos
       ADD one
       STA next

We can now compare the two adjacent values at position “pos” and “next” (=pos+1). Note the use of indirect addressing using the @ symbol to access the values stored at the address stored at position “pos” and “next”. To compare both values we perform a SUB (subtract) operation.
If the current value (@pos) is greater then the next value (@next) then the subtraction will be positive. If both adjacent values are equal then the subtraction will be null and there is no need to swap both values (BRZ pass). If not, if the subtraction is a positive number (>0) then we will swap both values: BRP swap. If not we will move on the next section of code to pass without swapping.

step   LDA @pos
       SUB @next
       BRZ pass
       BRP swap

To pass, we increment both pointers “pos” and “next” by 1 so that we can then repeat the process with the next two values (by branching to the “step” block of code). However, we also need to check if we have reached the end of the list (if the “next” pointer is pointing to the last value in the list. In this case we would need to check if we need to start a new iteration of the Bubble sort algorithm from the very start of the list, or whether we can stop here (if the list is already fully sorted). This check will be performed in the “repeat” block of code.

pass   LDA pos
       ADD one
       STA pos
       LDA next
       ADD one
       STA next
       LDA pos
       SUB last
       BRZ repeat
       BRA step

Below is the code used to swap both adjacent values (at position “@pos” and “@next”). This also sets the “sorted” flag to false, to indicate that the list may not be fully sorted yet and that a new iteration of the Bubble Sort will be needed.

swap   LDA @next
       STA temp
       LDA @pos
       STA @next
       LDA temp
       STA @pos
       LDA false
       STA sorted
       BRA pass

The “repeat” block of code is used to decide whether the list is fully sorted or whether a new full iteration of the list is needed to continue the sorting process. This is done by checking that the flag “sorted” is true or false. If it is true, then the list is sorted and we can stop the Bubble Sort algorithm by branching to the “exit” block of code. Otherwise we are going back to the star of the process by branching to the “loop” block of code.

repeat LDA sorted
       SUB true
       BRZ exit
       BRA loop

Finally, the “exit” block of code is used to inform the user that the list is now fully sorted. This is done by outputting the value 0 and stopping the process (HLT instruction).

exit   OUT
       HLT
Tagged with: