More results...

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

Airport Code Lookup Check

airport-signIn this challenge we will implement a small Python program to:

  • Ask the user to enter a 3-letter airport code (e.g. LHR) for one of the top 20 busiest airports in the world.
  • Output the full name of the airport matching the code.

For this program we will use the official codes from the International Air Transport Association (IATA).

To make our program more robust, we will implement a couple of validation checks used to check if an airport code is valid. Our validation routine will:

  • Automatically convert the user input (airport code) to uppercase
  • Ensure the airport code provided is exactly 3 characters long (Length Check)
  • Ensure the airport code provided is one of the top 20 airport codes (Lookup Check)

To implement our lookup check we will use a dictionary data structure containing all 20 airport codes and their full names.

A dictionary is a data structure which contains an unordered list of key/value pairs. In our examples the keys are the airport codes, the values are the full airport names. e.g.

airports = {"ATL":"Hartsfield–Jackson Atlanta International Airport",
            "PEK":"Beijing Capital International Airport",
            "DXB":"Dubai International Airport",
            "LAX":"Los Angeles International Airport",
            ...
           }

Notice the use of curly brackets in Python when creating a dictionary data structure.

With this dictionary we can then retrieve a single value by providing a key. e.g.

print(airports["DXB"])

The above line of code would output “Dubai International Airport” on screen.

We can also check if a key exists in a dictionary by using the keyword in. e.g.

if "DXB" in airports:
      print(airports["DXB"])
else:
      print("Airport code not recognised")

Python Code

Check the code below to validate a 3-letter airport code using both a length check and a lookup check.

Your Task

Your task is to create another dictionary called airlines which will contains twelve of the main international airlines with their 2-letter codes as follows:

Airline Code Airline
AA AMERICAN AIRLINES
AC AIR CANADA
AF AIR FRANCE
AI AIR INDIA
BA BRITISH AIRWAYS
DL DELTA AIR LINES
CA AIR CHINA
JL JAPAN AIRLINES
MS EGYPTAIR
QF QANTAS AIRWAYS
SQ SINGAPORE AIRLINES
UA UNITED AIRLINES

Your program should ask what airlines the end-user is flying with (using a 2 letter code input) and use the airlines dictionary to validate the user input and retrieve and display the full name of the airline company.

unlock-access

Solution...

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

My Class Register

class-register-clipboardFor this challenge we will create a program to be used by a teacher at a start of a lesson to take the register. The program will go through a class list and for each pupil in the list, will ask the teacher if the pupils is present (y) or absent (n).

The program will then output the total number of students in the class, the number of students present and the number of students who are absent.

Flowchart / Algorithm


We have designed the following flowchart for this program. This algorithm uses a list called pupils used to store the names of all the students in the class.
class-register-flowchart

Python Code


Your tasks is to type the Python code following the steps identified in the above flowchart.

unlock-access

Solution...

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

Pentagram Challenge

pentagon-circumcircleA polygon is a plane shape (2D) with straight lines. It consists of vertices and edges.

A polygon is regular when all angles are equal and all sides are equal. For instance a regular pentagon consists of 5 vertices and 5 edges of equal size. The vertices of a regular pentagon are equally spread on a circle. This outside circle is called a circumcircle, and it connects all vertices (corner points) of the polygon. The radius of the circumcircle is also the radius of the polygon. We can use the trigonometric formulas to work out the (x,y) coordinates of each vertex of a regular pentagon. (See picture on the right).

Using this approach, we can use a Python script to calculate the (x,y) coordinates of the 5 vertices of a regular pentagon and store them in a list of [x,y] sub-lists.

pentagon=[]
R = 150
for n in range(0,5):
  x = R*math.cos(math.radians(90+n*72))
  y = R*math.sin(math.radians(90+n*72))
  pentagon.append([x,y])

Star Shapes


pentagramA pentagram is a polygon that looks like a 5-pointed star. The outer vertices (points of the stars) form a regular pentagon. The inner vertices of the star also form a smaller “inner” regular pentagon.

We can hence use a similar approach to calculate the (x,y) coordinates of both “outer” and “inner” vertices of our pentagram.
pentagram-coordinates

Python Turtle


We have completed the code to calculate the coordinates of a regular pentagon (using the code provided above) and have created a function called drawPolygon() that uses Python Turtle to draw a polygon on screen.

Your Task


Adapt the above Python code to calculate the coordinates of all the vertices of a pentagram (star shape) and draw the pentagram on screen.

The output of your program should be as follows:
pentagram-star-shape

Extension Task


Use the shoelace algorithm to calculate the area of your pentagram.
unlock-access

Solution...

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

The Shoelace Algorithm

shoelace-formula-polygonThe shoelace formula or shoelace algorithm is a mathematical algorithm to determine the area of a simple polygon whose vertices are described by their Cartesian coordinates in the plane.

The method consists of cross-multiplying corresponding coordinates of the different vertices of a polygon to find its area. It is called the shoelace formula because of the constant cross-multiplying for the coordinates making up the polygon, like tying shoelaces. (See table below). This algorithm has applications in 2D and 3D computer graphics graphics, in surveying or in forestry, among other areas.

the-shoelace-formula

To apply the shoelace algorithm you will need to:

  • List all the vertices in anticlockwise order. (e.g. A,B,C,D,E) in a table, and note the x and y coordinates in two separate columns of the table,
  • Calculate the sum of multiplying each x coordinate with the y coordinate in the row below (wrapping around back to the first line when you reach the bottom of the table),
  • Calculate the sum of multiplying each y coordinate with the x coordinate in the row below (wrapping around back to the first line when you reach the bottom of the table),
  • Subtract the second sum from the first, get the absolute value (Absolute dfference |sum1-sum2|,
  • Divide the resulting value by 2 to get the actual area of the polygon.

shoelace-table

the-shoelace-formula-ABCDE

The Shoelace Algorithm using Python:


To implement the shoelace algorithm we will define a polygon as a list of vertices, listed in anticlockwise order. Each vertex will be a list of 2 values: its x and y coordinates.

Alternative Approach


The above algorithm requires the computer to calculate two different sums that could potentially lead to very high numbers. On occasion these numbers could generate an overflow error if they reach the maximum capacity of an integer value.

The Shoelace formula can be rewritten as follows:
the-shoelace-formula-v2

In this case the python code given above can be adapted to reflect this new formula and reduce the risk of creating an overflow error.

Your task is to tweak the above code to base the code on this alternative Shoelace formula.

unlock-access

Solution...

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

Sorting Algorithms using Python

sorting-algorithms-pythonComputers are often used to sort large amounts of data. Though this may seem like a simple task to complete, a lot of research has focused on finding the most effective algorithms to sort large amount of data.

Four of the most basic algorithms to sort a set of data are:

  • Insertion Sort Algorithm,
  • Bubble Sort Algorithm,
  • Selection Sort Algorithm,
  • Merge Sort Algorithm.
  • We have implemented each these algorithms below, using Python to sort a set list of values.

    Insertion SortBubble SortSelection SortMerge Sort

    Insertion Sort


    The insertion sort is an iterative algorithm (using nested loops).


    Bubble Sort


    The Bubble sort is an iterative algorithm (using nested loops).


    Selection Sort


    The selection sort is an iterative algorithm (using nested loops).


    Merge Sort


    The merge sort algorithm uses a recursive function.


Merge Sort Algorithm

Computers are often used to process large amounts of data. Some of the tasks they can be used for is to sort data sets in order, e.g. numerical order or alphabetical order. Though this may seem like a simple task to complete, a lot of research has focused on finding the most effective sorting algorithm, especially when working on large data sets.

One of the key sorting algorithms is called a merge sort and is based on a divide and conquer approach.

Merge-Sort-Algorithm

Your Task


Practise sorting lists of numbers using a Merge sort: (Open in new window)

Tagged with:

Bubble Sort vs. Insertion Sort

sorting-algorithmsComputers are often used to sort large amounts of data (e.g. numerical order or alphabetical order). Though this may seem like a simple task to complete, a lot of research has focused on finding the most effective approach to sort data.

Two of the most basic algorithms used to sort data are the Bubble Sort Algorithm, and the Insertion Sort Algorithm.


Insertion-sort-1-9

Insertion Sort Algorithm


To start with, the algorithm considers the first value of a list as a sorted sub-list (of one value to start with). This iterative algorithm then checks each value in the remaining list of values one by one. It inserts the value into the sorted sub-list of the data set in the correct position, moving higher ranked elements up as necessary.

This algorithm is not always very efficient and is mostly recommended when sorting a small lists of values or a list that is already almost sorted.

You can check our Python implementation of this algorithm on this blog post.


Bubble-sort-1-9

Bubble Sort Algorithm


The algorithm starts at the beginning of the data set. It compares the first two value, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent values to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass.

This algorithm is particularly useful when you need to find the top x values of a list.

You can check our Python implementation of this algorithm on this blog post.


Your Task


Practise sorting lists of numbers using both the Insertion sort and the Bubble sort algorithms using the two tabs below:
Insertion SortBubble Sort
Tagged with:

Random Password Generator

passwordFor this challenge, we will use a Python script to generate a random password of 8 characters. Each time the program is run, a new password will be generated randomly. The passwords generated will be 8 characters long and will have to include the following characters in any order:

  • 2 uppercase letters from A to Z,
  • 2 lowercase letters from a to z,
  • 2 digits from 0 to 9,
  • 2 punctuation signs such as !, ?, “, # etc.

To solve this challenge we will have to generate random characters and to do so we will need to use the ASCII code.

ASCII Code


The ASCII code (Pronounced ask-ee) is a code for representing English characters as numbers, with each character assigned a number from 0 to 127. For example, the ASCII code for uppercase M is 77. The extended ASCII code contains 256 characters (using numbers from 0 to 255).

To see a list of the most useful ASCII codes you can download our simplified ASCII helpsheet.

Using Python you can easily access ASCII values of a character using the ord() function. For instance ord(“M”) returns 77 and chr(77) returns “M”

When looking at the list of most widely used ASCII codes you will notice that all uppercase letters from A to Z have an ASCII code between 65 (=A) and 90 (=Z). To generate a random uppercase letter between A and Z we can hence use the following Python code:

import random
uppercaseLetter=chr(random.randint(65,90)) #Generate a random Uppercase letter (based on ASCII code)

Flowchart


To help you solve this challenge, we have completed the flowchart of our random password generator algorithm:
random-password-generator-flowchart
This algorithm is an example of:
sequencing-label

Python Code


You can use the flowchart above as well as our ASCII helpsheet 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
Tagged with: ,

Prolog – Family Tree

family-treeProlog 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)


Check the following knowledge base used to store the information that appears on a family tree:

/* Facts */
male(jack).
male(oliver).
male(ali).
male(james).
male(simon).
male(harry).
female(helen).
female(sophie).
female(jess).
female(lily).

parent_of(jack,jess).
parent_of(jack,lily).
parent_of(helen, jess).
parent_of(helen, lily).
parent_of(oliver,james).
parent_of(sophie, james).
parent_of(jess, simon).
parent_of(ali, simon).
parent_of(lily, harry).
parent_of(james, harry).

/* Rules */
father_of(X,Y):- male(X),
    parent_of(X,Y).

mother_of(X,Y):- female(X),
    parent_of(X,Y).

grandfather_of(X,Y):- male(X),
    parent_of(X,Z),
    parent_of(Z,Y).

grandmother_of(X,Y):- female(X),
    parent_of(X,Z),
    parent_of(Z,Y).

sister_of(X,Y):- %(X,Y or Y,X)%
    female(X),
    father_of(F, Y), father_of(F,X),X \= Y.

sister_of(X,Y):- female(X),
    mother_of(M, Y), mother_of(M,X),X \= Y.

aunt_of(X,Y):- female(X),
    parent_of(Z,Y), sister_of(Z,X),!.

brother_of(X,Y):- %(X,Y or Y,X)%
    male(X),
    father_of(F, Y), father_of(F,X),X \= Y.

brother_of(X,Y):- male(X),
    mother_of(M, Y), mother_of(M,X),X \= Y.

uncle_of(X,Y):-
    parent_of(Z,Y), brother_of(Z,X).

ancestor_of(X,Y):- parent_of(X,Y).
ancestor_of(X,Y):- parent_of(X,Z),
    ancestor_of(Z,Y).

Note that \+ means NOT

Queries


We can now query this database. For each of the queries listed below, what do you think the computer will return?

True or False Queries:
The following queries would return either True or False.

?-mother_of(jess,helen).
?-brother_of(james,simon).
?-ancestor_of(jack,simon).
etc.

Other Queries:
The following queries would return a solution which could be either:

  • A unique value
  • A list of values
  • False if no solution can be found
?-mother_of(X,jess).
?-parent_of(X,simon).
?-sister_of(X,lily).
?-ancestor_of(X,lily).
etc.

Your Task:


Use a range of queries, similar to the one above to interrogate the knowledge base and complete the family tree provided below.

To run your queries you will need to use the online Prolog environment:
https://swish.swi-prolog.org/p/prolog-family-tree.pl

Here is the template for the family tree for you to complete:
prolog-family-tree

Tagged with:

Computer Networks Concepts

Click on the picture below to check your knowledge of key Network concepts: Network components and Internet concepts.


network-concepts

Network ConceptsOpen Domino Activity
 
Tagged with: