More results...

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

Short Path Algorithm Practice

Before completing this task, you will need to familiarise yourself with the following 2 algorithms used to find the shortest path between two nodes of a weighted graph:

Dijkstra’s Short Path Algorithm

For each of the weighted graph below, complete the table below to show the steps needed to find the shortest path between node A and node Z using the Dijkstra’s Short Path Algorithm. Note that on these graphs, the weight of each edge represents the distance in miles between two nodes.

Graph #1Graph #2Graph #3Graph #4

Shortest Path?

Length?


Shortest Path?

Length?

Shortest Path?

Length?

Shortest Path?

Length?

Node Status Shortest Distance from A Previous Node
A
B
C
D
E
F
G
H
Z

A* Algorithm

On the graphs below, the heuristic values specified for each node of the graph represent the distance in a straight line (as the crow flies) between the node and the destination node (Z).

Graph #1Graph #2Graph #3Graph #4
Shortest Path?

Length?

Shortest Path?

Length?

Shortest Path?

Length?

Shortest Path?

Length?

Node Status Shortest Distance from A Heurisitic Distance to Z Total Distance Previous Node
A
B
C
D
E
F
G
H
Z

TCP/IP Stack: Network Layers and Protocols

The TCP/IP Stack is a model that governs how data is transmitted from one computer to another via an IP network such as the Internet.

Internet communication includes using a web browser to access a webpage from a websever, sending or downloading an email from a mail server, uploading files to a server using an FTP client, etc.

For all these Internet communications, the TCP/IP Stack is used to show the different protocols used to format data to enable its transmission between computers.

A protocol is a set of rules required for two computers to communicate over a network.

A layer is a group of protocols focusing one one stage of the data transmission.

The TCP/IP Stack consists of 4 Layers:

  • Application Layer
  • Transport Layer
  • Internet/Network Layer
  • Physical/Data/Link Layer

Application Layer

The application layer is used to format the data so that it can be processed by the application(e.g. web browser, email client) being used for the communication. For instance:

  • HTTP and HTTPS protocols are used to access a webpage via a web-browser
  • The SMTP protocol is used to send e-mails between mail servers
  • The IMAP and POP3 protocols are used to retrieve emails from a mail server
  • The FTP protocol is used to transfer files between two computers

Some protocols such as HTTPS are also used to make sure the data is encrypted before being transmitted (passed down to the next layer).

Transport Layer

The transport layer is used to implement packet switching.

The purpose of this layer is to split the data being transmitted in to data packets. Each packet will have its own header with information about the packet being sent, its position in the transfer, the protocol and port used.

This layer is also responsible for checking packets when they are received. This is called Transfer Control (TCP Protocol). If a packet is missing or has been corrupted, the receiving computer will automatically ask the sending computer to resend the missing/corrupted packet.

Internet Layer

This layer is also known as the Network layer. Each packet is assigned the IP address of the source (sending computer) and of its destination (receiving computer) so that the packet can be routed through the network/Internet.

On the Internet, data packets are being redirected by routers till they reach their destination.

Link Layer

This layer is also known as Physical Layer. The aim of this layer is to convert the data packets into an electric current going through a copper cable (Ethernet, Coax, Phone line, etc.), an electromagnetic radio wave (wireless transmission) or a light beam (optic fibre).

The protocols used on this layer depend on the type of connection/link used to transfer the data: e.g.

  • WiFi, 3G/4G/5G, Bluetooth are examples of wireless protocols
  • Ethernet and ADSL are examples of protocols used for wired communication

TCP/IP Stack Drag and Drop

Complete the following drag and drop activity to check your understanding of the TCP/IP Stack!

TCP/IP StackOpen in New Window

Tagged with:

Snow Poem Algorithm

The following algorithm is inspired by a poem by Brian Bilston called “snow poem”. On this poem, each word represents a snowflake gently and randomly falling from the sky. On the last verse of this poem, you can see how the snow is starting to settle on the ground!

The aim of this challenge is to investigate a range of string manipulation techniques using Python including:
Splitting a string into a list, using a special character (e.g. space or “/” character)
String concatenation techniques using the * and + operators
Retrieving the length of a string using the len() function.

Here is the Python code for our Snow Poem algorithm:

Christmas Tree

Using a similar approach, we created an algorithm to reproduce the poem “Needles” by the same author.

Here is the Python code for the poem “Needles”:

There is no coding task attached to this algorithm. If you like this code, you may want to investigate the following challenges:

Programming Terminology – Drag and Drop


To be a good carpenter, you need to be able to identify and select the right tools to complete your project. For instance, the main wood working tools used by carpenters are:

Chisel, Hand Saw, Hammer, Screwdriver, Hand Plane, Caliper, Level, Clamp, Circular Saw, Jigsaw, Orbital Sander, Palm Sander, Tape Measurer, Miter Gauge, Router, Band Saw, Power Drill, Drill Press, Grinder, etc.

It’s the same with programming. To be a good programmer, your need to be able to identify all the tools that are available to build a computer program. If you can name these tools, you will then be able to select the right tool when you need them!

When using procedural programming with a high level programming language like Python, the main tools of the programmer are:

    Sequencing,
    Iteration,
    Selection,
    Variables,
    Constants,
    Data Types (Integer, Float, String, Boolean) & casting values,
    Computing Operators (assignment operator, arithmetic operators, comparison operators, Boolean operators)
    Data Structures (e.g. lists and arrays)
    String manipulation techniques (incl. String concatenation)
    Subroutines (e.g. Procedures and Functions)
    Libraries (e.g. random library, time library, etc.)
    Etc.

Task 1: Drag and Drop

Complete the fill in the gaps activity below to label all the programming terminology used in this Python program:


Programming TerminologyOpen in New Window

Task 2: Python Coding

Code this program online using trinket.io.

Task 3: Returning the change!

Update the above code, so that, when the user overpays, the program returns the change. For instance, if your customer overpays by £14, the output of your code would be:

You overpaid by £14. Here is your change:
£10 banknote
£2 coin
£2 coin

unlock-access

Solution...

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

Laser Maze Game in Python

In this Python programming challenge, we are going to recreate the game “Laser Maze”.

The aim is to redirect a laser beam across a given stage in order to reach the exit gate of the stage.

The laser can only travel in four directions:

  • Up
  • Right
  • Down
  • Left

The stage/maze is a 2D grid consisting of 12×12 tiles (including the outside walls of the room):

The following rules will apply when generating the stage:

  • The source of the laser beam will be randomly positioned on the left wall of the room and the laser will be aiming to the right.
  • The exit gate of stage will be randomly positioned on the right wall of the room.
  • 3 Bombs will be randomly placed on three tiles of the stage.

To solve the level, the user will have to place some reflectors on the stage using the following rules:

  • Reflectors can only be placed on empty tiles. They cannot be placed on existing walls, bombs, laser source or exit gate.
  • There will be two types of reflectors: // and \\ which will redirect the laser beam by 90 degrees either clockwise (\\) or anti-clockwise (//)

Structure Diagram (Decomposition)

Here is the structure diagram for our Laser Maze Game:

From this structure diagram, we can generate the following checklist:
Initialise 12×12 empty maze
Place Laser Source
Place Exit Gate
Place Bombs
Display maze
Player inputs row and column numbers and type of reflector
Place reflectors on the maze
Repeat process (for any additional reflectors)
Shooting: Start Laser Beam at Source
Trace laser in all four directions (right, left, up, down)
Detect collision with bombs
Detect collision with walls
Detect collision with laser source
Detect collision with exit gate
Detect collision with reflectors
Redirect laser beam (when laser collides with a reflector)
Output “Level Complete” message or “Game Over Message”

Python Code

We have started the code for our laser game but our code is incomplete. Your task is to complete this game to allow the user to solve the level by placing reflectors on the 2D grid to redirect the laser beam either clockwise or anti-clockwise.

Extension Task

Your extension task is to implement a scoring system.
At the start of the game, the user has 100 points.
Each reflection wall used costs 20 points.
Once a level is complete, the user should earn 50 points.
Once a level is complete, the user should automatically be presented with a new level.
The game stops when the user hits a wall or a bomb.

unlock-access

Solution...

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

Battle of the Knights

For this Python programming challenge, you are going to create a Battle game where two knights will fight each other till death!

Your game will use a text-based user interface (using ASCII art to represent the knights) and will produce a frame based animation of the battle scene:

Here is a structure diagram of the whole game:

Using this structure diagram we can generate the following to do list for you to complete this game step by step:
Generate random knight names for both players
Initialise both health scores to 100
Randomly pick an action for each knight (attack, defend or rest)
Display the battle scene (as stickmen based on the action of each knight)
Update health scores
Display knights’ names and health scores
Repeat process as long as both health scores are positive
Stop the battle as soon as at least one health score is lower or equal to zero
Identify if there is a winner or a draw (when both players have a health score lower or equal to 0)
Output the last scene of the battle and the name of the knight who won the battle

Python Code

To get started with this project, we will reuse the code from the “Knight Name Generator” challenge.

Note that to create a frame based animation, you can use both the time library (to define the delay between two frames) and the os library (to clear the screen between each frame). For instance, see how this code displays a random number every 1 second.

import random, time, os
while True:
   print(random.randint(0,10))
   
   time.sleep(1)
   os.system("cls")

Your task is to complete the code below to implement all aspects of this game using the above checklist:

Extension Task

Re-organise your code to make use of OOP concepts.

You should do so by creating a Knight class to store the name, health and state of your knight as properties of the Knight class and use a few methods to let your knight randomly pick an action (new state) or to draw your sprite on screen.

unlock-access

Solution...

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

Knight Name Generator

In this Python challenge, we are going to create two functions to generate the name of a Knight and their coat of arms.

Name Generator

Let’s first generate the name of our knight. To do so we will code a sequencing algorithm that will use:

  • The random library to randomly pick a first name and a nickname from a list of possible first names and another list of nicknames.
  • String concatenation to combine the first name and the nickname together to produce the full name of our knight.

We will code this algorithm inside a function called knightNameGenerator(). This functions will generate and return the name of our knight so that we can store it in a variable and use it later on in our code.

Let’s investigate the code of our knightNameGenerator() function:

import random

def knightNameGenerator():
  firstnames = ["Lancelot","Charles","Henry","William","James","Richard","Edward"]
  nicknames = ["Brave","Horrific","Courageous","Terrific","Fair","Conqueror","Victorious","Glorious","Invicible"]
  
  firstname = random.choice(firstnames)
  nickname =  random.choice(nicknames)
  return firstname + " The " + nickname 

We can then write a short algorithm to test our function. Here is the full Python code for you to review and test:

Coat of Arms Generator


In the medieval times, each knight had a coat of arms: symbol used to represent their family. Your task consists of generating a new function called generateCoatOfArms() that will randomely pick and combine a colour and an animal from two separate lists of possible values and combine them together (using string concatenation) to generate and return the coats of arms of both player 1 and player 2.

You will need to complete this code in the above trinket frame.

To help you with this code you may use the following two lists of possible values:

colours = ["Red","Golden","Blue","Purple","White","Silver"]
animals = ["Lion","Dragon","Unicorn","Horse","Tiger"]

For instance, the output of your program could be:

  • Player 1: Your name is William The Brave
  • Your coat of arms is a Red Lion
  • Player 2: Your name is Lancelot The Victorious
  • Your coat of arms is a Golden Dragon

Extension Task 1:

Tweak your new generateCoatOfArms() function two generates two random colours to be used when generating your coat of arms. If both colours are different the output would be:

  • Player 1: Your name is William The Brave
  • Your coat of arms is a Red and White Lion

If both randomly picked colours are the same then, only one should be used to describe the coat of arms:

  • Player 2: Your name is Lancelot The Victorious
  • Your coat of arms is a Purple Unicorn

Extension Task 2:

Create one more function to randomly generate the favourite weapon of your knight e.g. iron mace, golden flail, silver axe, silver sword, wooden shield, etc.

  • Your favourite weapon is an iron mace.


Add more functions to describe the top qualities of your knight or where they live e.g. haunted castle, hidden mansion, fortified tower, etc.

  • You are loyal and combative
  • You live in a haunted castle

unlock-access

Solution...

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

2018 World Cup – Goals Analysis

For this challenge we will investigate how to retrieve and filter data from a CSV file to perform a goals analysis of the 2018 Football World Cup.

We have collated a CSV files of all the goals scored during this world cup and stored this information in a CSV file, using the semi-colon as a separator. The data is formatted as follows:

player;country;time;

On this data, time represents the minute in the game when the goal was scored.

You can preview and download the file:

TextFile
goals.txt

Our aim is to write a collection of subroutines that will be used to extract and display relevant information from this text file. We will then display a menu of options for the user to select what goals analysis to perform. Here will be the options from our menu:

  • A: Total number of goals scored by a given country
  • B: Total number of goals scored by a given player
  • C: List the name of all the players who scored for a given country
  • D: Total number of goals by all countries
  • E: Total number of goals scored during the first half (45 minutes)
  • F: Total number of goals scored during the second half (45 minutes to 90 minutes)
  • G: Total number of goals scored during extra time (after 90 minutes of play)
  • X: Exit?

File Handling in Python

When using text file in Python, you should always start by opening the text file using the right file access mode. In this case will will open the file in read mode (“r”).

file = open("goals.txt","r")

We can then access each line of the file one at a time using a for loop:

for line in file:
    print(line)

Because our file is a CSV file, each line of the file will contains several fields (in our case three fields: player, country, minutes). We can extract this data by splitting the line using the separator “;”.

for line in file:
    data = line.split(";")
    player = data[0]
    country = data[1]
    minutes = int(data[2])
    print(player + " from " + country + " scored a goal at the " + str(minutes) + "th minutes")

You can filter the data by using an if statement. This code will perform a linear search to find all the goals scored by Spain:

for line in file:
    data = line.split(";")
    player = data[0]
    country = data[1]
    minutes = int(data[2])
    if country=="Spain":
        print(player + " from " + country + " scored a goal at the " + str(minutes) + "th minutes")

Once you have completed your analysis, do not forget to close the text file:

file.close()

Python Code

We have started the code for you, but you will to add more subroutines to implement all menu options.

Extension Task 1: World Cup Quiz


Write a Python program that randomly pick two countries from the list of countries which took part in the 2018 world cup.

Ask the user to guess which of the two countries scored the most goals during this world cup. Check their answer to see if they guessed it right.

Here is some code to get your started. First we will generate a list of all countries which scored goals during the 2018 world cup:

countries = []

file = open("goals.txt","r")

for line in file:
    data = line.split(";")
    country = data[1]
    if country not in countries :
        countries.append(country)

file.close()

print(countries)

Then to randomly select a country from this list, we will use the random library:

import random
randomCountry = random.choice(countries)

Note that you should add the import statement at the very top of your code.

Extension Task 2: Top Scorers


Complete your code by adding two options to your main menu as follows:

  • H: List the total number of goals scored for each country
  • I: Which country scored the most goals?
  • J: Which player scored the most goals?

Implementing these two subroutines will be more advanced than just performing a linear search through the text file. Our tip is to use a hash table (dictionary data structure) to store the total number goals scored by each country to then find out which country scored the highest number of goals.

unlock-access

Solution...

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

The Retro Gaming Internet Café

A youth club has decided to transform their club into a Retro Gaming Internet Café for the week-end. Their aim is to let people join in and play online retro games such as Pong, Pacman or Space Invaders, on desktop or laptop computers.

Amina, the youth club leader, has found a box a network hardware that she will use to set up the Local Area Network (LAN) for the week-end. The box contains:

  • An ADSL router that can connect a LAN to the Internet via the phone line,
  • A firewall
  • A hub with 10 ethernet ports
  • A Wireless Access Point
HubRouterFirewallWAP
Here is a picture of the network hub with 10 ethernet ports.

Here is a picture of the ADSL router, that can connect a LAN to the Internet via the phone line.

Here is a picture of the firewall, used to make the network more secure, by blocking suspicious incoming and outgoing traffic.

Here is a picture of the Wireless Access Point (WAP).

Amina has also collected a set of computers from the members of the club. So far she has managed to retrieve:

  • 10 desktop computers all with a ethernet Network Interface Card (NIC). These do not support wireless transmission.
  • 3 laptop computers all with a Network Interface Card (NIC) that can connect either wirelessly or via an Ethernet cable.
  • An inkjet printer with an Ethernet port

Amina would like to design the topology of her computer network to find out how to connect all these computers and hardware devices together so that:

  • The maximum number of computers are connected to the network, either using an Ethernet cable or wirelessly, when possible
  • All computers have access to the Internet
  • The network is secure/protected from external hackers
  • All computers have access to the printer for the user be able to print their score sheets

She was told that, considering her equipment, she should use a Star topology for her network.

Your Task

Use our online network designer tool to draw a network design meeting Amina’s requirements.

Did you manage to connect all the computers to the network? If not, Amina can bring an extra hub which has 8 ethernet ports. Can you produce another diagram to demonstrate how to connect this extra hub to the network and find out in total, how many computers could be connected to this new network?

Design Your Own Network Online
unlock-access

Solution...

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

A Python game of Noughts and Crosses

In this blog post, we will focus on using a 2D array to create a 3×3 game of noughts and crosses. We will investigate the code using a step by step approach.

You can follow the steps described below and recreate the code yourself using your preferred IDE or using our online Python IDE.

Step 1: Welcome Banner

Let’s start our game by creating a banner to introduce the game. To do so will create a procedure called displayBanner() that will output the banner on screen.

#A Procedure to display a welcome banner
def displayBanner():
  print("XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXO")
  print("O                              X")
  print("X     Noughts and Crosses      O")
  print("O                              X")
  print("XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXO")
  print("")
    

We will then create the main program by calling our subroutine.

#Main Program Starts Here
displayBanner()

Step 2: Defining the noughts and crosses grid as a 2D array

We will now use a 2D array to store the position of our noughts and crosses on a 3×3 grid. In Python, you can create a 2D array using a list of lists.

We will use a blank space ” ” for each value of the grid to indicate that each cell of the grid is empty to start with.

#Main Program Starts Here
displayBanner()
#Defining the grid a 2D array (3x3)!
grid = [[" "," "," "],[" "," "," "],[" "," "," "]]

Step 3: Displaying the grid on screen

At the top of our code, we are going to create a new subroutine used to display the 2D grid on screen using the following code:

#A procedure to display the noughts and crosses grid
def displayGrid(grid):
  print(" " + grid[0][0] + " | " + grid[0][1] + " | " + grid[0][2])
  print("-----------")
  print(" " + grid[1][0] + " | " + grid[1][1] + " | " + grid[1][2])
  print("-----------")
  print(" " + grid[2][0] + " | " + grid[2][1] + " | " + grid[2][2])

We will then edit our main program to call our new subroutine.

#Main Program Starts Here
displayBanner()
#Defining the grid a 2D array (3x3)!
grid = [[" "," "," "],[" "," "," "],[" "," "," "]]
displayGrid(grid)

Step 4: Player 1’s Turn

The game is now all set up and the next step is to ask for player 1 to decide where to place their cross “X”.

To do so, we will ask the user to input two values: the indexes of the row and of the column of the cell of their choice. Both indexes will be given as a number between 0 and 2:

Before deciding to place a token at the given row and column index, the program should check to see if the selected cell of the grid is empty. If not, it should ask the user to select a different row and column index.

The program will then set an “X” within the grid at the given row and column index before displaying the new grid on screen.

print("Player X: Your Turn!")
row = int(input("Enter the row index: 0 , 1 or 2"))
col = int(input("Enter the col index: 0 , 1 or 2"))

#Check if this cell is empty or not. If is is not empty the user will have to select another cell.
while grid[row][col]!=" ":
   print("Sorry this cell is already taken... Try again!")
   row = int(input("Enter the row index: 0 , 1 or 2"))
   col = int(input("Enter the col index: 0 , 1 or 2"))

#Place the cross on the grid using the chosen row and column index    
grid[row][col] = "X"

#Display the new grid on screen
displayGrid(grid)

Step 5: Player 2’s Turn

We are now going to ask player to input their row and column index to decide where to place their nought “O”.

To do so we can reuse the same code as used in step 4.

print("Player O: Your Turn!")
row = int(input("Enter the row index: 0 , 1 or 2"))
col = int(input("Enter the col index: 0 , 1 or 2"))

#Check if this cell is empty or not. If is is not empty the user will have to select another cell.
while grid[row][col]!=" ":
   print("Sorry this cell is already taken... Try again!")
   row = int(input("Enter the row index: 0 , 1 or 2"))
   col = int(input("Enter the col index: 0 , 1 or 2"))

#Place the cross on the grid using the chosen row and column index    
grid[row][col] = "O"

#Display the new grid on screen
displayGrid(grid)

Step 6: Playing against the computer

We can tweak the code from the above step, so that the computer decides where to place its token. To do so we will let the computer randomly select a row and a column index by generating two random values between 0 and 2.

To generate a random number you will first need to import the random library by adding the following line of code, at the very top of your program.

import random

Then we will replace the input statements to generate random values instead.

print("Player O: Your Turn!")
row = random.randint(0,2)
col = random.randint(0,2)

#Check if this cell is empty or not. If is is not empty the user will have to select another cell.
while grid[row][col]!=" ":
   print("Sorry this cell is already taken... Try again!")
   row = random.randint(0,2)
   col = random.randint(0,2)

#Place the cross on the grid using the chosen row and column index    
grid[row][col] = "O"

#Display the new grid on screen
displayGrid(grid)

Step 7: Using a loop to let each player place all their tokens

We now need to repeat steps 4 and 5 (or 6) several times to let the players complete the grid by placing 9 tokens in total. We will do so using a for loop that will be applied to all the code from step 4 and 5/6. (From line 25 to 55).

To alternate which turns it is to play we will use the counter of our for loop and if this counter is even we will let player 1 have a go, otherwise (if it is odd) player 2 will have a go.

for i in range(0,9):    
    if i%2 == 0: #check if i is an even number
       print("Player X: Your Turn!")
       ...
    else:
       print("Player O: Your Turn!")
       ...
       
 

Step 8: Checking if we have a winner!

We will now add a new subroutine to our code to check a grid and find out if the grid contains three consecutives “X” or “O”, in a row, a column or a diagonal. We can exit the game if it does.

def checkGrid(grid):
   #Checking the first row...
   if grid[0][0]=="X" and grid[0][1]=="X" and grid[0][2]=="X":
        print("Three Xs in a row.")
        exit()
   elif grid[0][0]=="O" and grid[0][1]=="O" and grid[0][2]=="O":
        print("Three Os in a row.")
        exit()
   #Checking the second row...
   if grid[1][0]=="X" and grid[1][1]=="X" and grid[1][2]=="X":
        print("Three Xs in a row.")
        exit()
   elif grid[1][0]=="O" and grid[1][1]=="O" and grid[1][2]=="O":
        print("Three Os in a row.")
        exit()
   #Checking the third row...
   if grid[2][0]=="X" and grid[2][1]=="X" and grid[2][2]=="X":
        print("Three Xs in a row.")
        exit()
   elif grid[2][0]=="O" and grid[2][1]=="O" and grid[2][2]=="O":
        print("Three Os in a row.")
        exit()
   
   #Checking the first column
   if grid[0][0]=="X" and grid[1][0]=="X" and grid[2][0]=="X":
        print("Three Xs in a column.")
        exit()
   elif grid[0][0]=="O" and grid[1][0]=="O" and grid[2][0]=="O":
        print("Three Os in a column.")
        exit()
      
   #Checking the second column
   #... complete the code here
   
   #Checking the third column
   #... complete the code here

   #Checking the first diagonale
   #... complete the code here

   #Checking the second diagonale
   #... complete the code here

We should then call this procedure as soon as a new nought or crosses is added to our grid. For instance, at the end of player 1’s turn, we can use the following lines:

grid[row][col] = "X"

#Display the new grid on screen
displayGrid(grid)

#Find out if there is a winner
checkGrid(grid)

And at the end of player 2’s turn:

grid[row][col] = "O"

#Display the new grid on screen
displayGrid(grid)

#Find out if there is a winner
checkGrid(grid)
unlock-access

Solution...

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