More results...

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

Work Life Balance (HTML, CSS & JS Challenge)

When your browser displays a webpage on screen it uses 3 different programming languages called HTML, CSS and JavaScript. We call the combination of these three languages “client-side web technologies”.

Each of the three language has its own syntax and purpose:

  • HTML uses <tags> and its purpose is to add content on the page such as text, pictures, and video clips.
  • CSS is used to customise the look and feel of the page by defining the position of each element on the page, defining the layout of the page as well as formatting text, pictures and other components on the page.
  • JavaScript is used to add user interaction to the page. JavaScript can be linked to HTML tags through various events such as the onClick event of a button.

Each of these languages are based on web standards defined by the World Wide Web Consortium W3C. As a consequence these languages are recognised by all the main web-browsers including Google Chrome, Microsoft Edge, Modzilla Firefox, Safari, etc. on various platforms (Windows, MacOs, Linux, Android etc.)

The Following codepen provides a clear demonstration of the syntax and purpose of HTML, CSS and JavaScript and shows how JavaScript can interact with various HTML tags.

See the Pen
Untitled
by 101 Computing (@101Computing)
on CodePen.

Your Challenge:


Add three more slider controls, each with a ranging from 0 to 255, to pick an RGB colour code and apply this colour code to the colour of the font used to display the text “Work Life Balance”. You will have to click in the top right corner (“Edit on CodePen”) to be able to tweak this code.


unlock-access

Solution...

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

The Birthday Paradox

The birthday paradox is based on a counter-intuitive fact that in any class of 23 students or more, there is a higher probability of having at least two students sharing the same bithday.

Considering that there are 366 different possible dates in a year (leap year), you may first predict that it would take a group of 183 students (50% of 366) to reach a 50% probability of at least two students sharing the same birthday. However this prediction would be wrong as this is not how the probabilities work in this case. You can use this page to find out more how to work out that with a class size of only 23 students, there is a probability of 50% that at least two students share the same birthday.

Python Challenge

For this Python challenge we will create a statistical simulation program to test the Birthday Paradox. Our aim is to determine whether the actual probabilities match the predicted probabilities by showing that, with a group of 23 students or more, the probability of having at least two students sharing the same birthday will be at least 50%.

We have started a program to help you with this challenge (See trinket window below). So far our program will:

  1. Generate a class list of students (e.g. 23 students or more)
  2. Use a randomDate() function to generate random birthdays for each of our students
  3. Store the lists of birthdays in a list
  4. Output the list of students with their randomly generated birthdays

Your task is to complete this code to:

  • Work out if, in this list of students, at least two students share the same birthday, and if so output their names and birthdays.

You will then be able to run this code several time to check whether, with a group of 23 students or more, you obtain a 50% or above chance of having at least two students sharing the same birthday. Note that you could also get the program to automatically repeat the experiment several times and calculate the resulting statistic (e.g. out of 10 experiments).

Below is the code to complete…

unlock-access

Solution...

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

Elastic Collision in a Pool Game

A range of video games use elastic collision formulas to predict the change of velocity of two objects when a collision occurs.

Elastic collision occurs when two objects are colliding and the total kinetic energy of the two objects remains the same. In reality, most collisions between two objects would result in some loss of energy (inelastic collision). However in some contexts, such as when two rigid billiard balls are colliding, this loss of energy is negligeable. In a video game of pool we would therefore implement an algorithm based on an elastic collision.

Let’s investigate how we can implement an elastic collision in a computer animation or a video game.

Velocity Vector

In a frame based game, most moving sprites would have a set of coordinates (x,y) to inidicate their position on the screen as well as a vaolcity vector (vx,vy) to indicate used to increment the (x,y) coordinates between two frames of the game and hence implement the movement of the sprite.

1 Dimensional Elastic Collision

Let’s consider two perfectly elastic balls of masses m1 and m2 moving along the same straight line with velocities u1 and u2.

Our aim is to calculate the velocity v1 and v2 of these two balls after the collision.

Conisidering that both momentum and kinetic energy are conserved quantities in an elastic collision, we can deduct the following two formulas:

Conservation of momentum

Conservation of kinetic energy

We can use both these formulas to calculate the velocity vectors v1 and v2 of the two colliding objects after the collision:

Note that these equations can be simplified when both colliding objects have the same mass: m1=m2. In this case we can use the following simplified formulas:

2 Dimensional Elastic Collision

In a 2-dimension environment, the velocity vectors may not be aligned on the same straight line.

We can however decompose the velocity vectors to identify the component of the velocity that is going along the straight line joining the centre of both moving balls (Purple vectors on the above diagram) and the component that is perpendicular to this straight line (Grey vectors on the above diagram). The first component will be affected by the elastic collision using the 1-Dimensional model/formulas whereas the second component will not be affected by the collision.

In order to calculate the 2 components of our velocity vectors (purple and grey vectors) we will first need to perform a rotation by θ, the angle that can be calculated using the (x,y) cartesian coordinates of the centre of both moving objects as follows:

We will then rotate our velocity vectors by θ as shown on the diagram below. Note however, that we would apply the same rotation for both velocity vectors (red and blue balls).

The formulas to perform a 2D rotation are as follows: (You can find out more about these formulas on this page)
where (Vx,Vy) represents the velocity vector (vx,vy) after the rotation.

We can now apply the 1-dimensional elastic collision formulas to the Vx (purple component) of the velocity for each moving object, whereas the Vy components will not be affected by the elastic collision.

And then we will need to rotate our new velocity vectors by to cancel out the previous rotation.

2-Dimensional Elastic Collision Demonstration

To see how the above formulas can be implemented, we have created a demo using JavaScript. You can investigate this code further to identify how the steps described above have been implemented.

In our demo, all the moving objects have a different mass, pro-rata of their size (radius).

Note that this code could be simplified further using objects of the same mass as this would be the case in a game of pool!

Finally, you will notice that this code also applies some formulas to the velocity vectors of each ball to let the balls bounce against the edge of the canvas. These formulas are explained on this page.

Your Task

Your task consists of tweaking the above code (Click on “Edit On Codepen” button in the top right corner of the above codepen frame) in order to create a pool table with:

  • 7 yellow balls
  • 7 red balls
  • 1 black ball
  • 1 white ball

Note that, in a game of pool, all balls have the same mass and size. You can hence simplify the code to use the simplified 1-dimensional elastic collision formulas.

About this task: The aim of this challenge is not to create a full game of pool but just to tweak the above code to make sure that the canvas contains 16 balls of the right colour and of the same weight/size. In a full game of pool, other features would need to be considered such as, implementing the correct size of the pool table, adding pockets and detecting when balls fall into these pockets, adding friction to slow down the rolling balls and adding a mechanism for the player to aim/shoot. All of these features are not part of this task.

unlock-access

Solution...

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

The Monty Hall Problem

The Monty Hall problem is a counter-intuitive brain teaser based on probabilities.

This puzzle is named after Monty Hall, the TV presenter of “Let’s Make a Deal”, an American TV show (known as “Deal or No Deal” in the UK) where contenders swap boxes of different values in order to win a prize.

In a similar approach, the aim of the Monty Hall puzzle is to try to win a car by knocking on the right door. The player is presented with three closed doors. Behind one of these doors is a luxurious car. Behind each of the other two doors is a goat!

Here is how the game proceeds:

  • You first pick a door. It could be that you picked the door with the car but you do not know that yet!
  • The game show host examines the other two doors and opens one with a goat. (Note that when both doors are hiding a goat, the presenter picks one of these doors randomly.)
  • You then need to make a decision: You can either stick with your initial guess and open the door to see if you win the car. Alternatively, you can decide to switch your door with the other closed door!

You can give it a go using our interactive game below:

What are the Odds?

When being asked whether to stick to your first guess or change your mind, there are only two closed doors left: One door hiding a goat and one door hiding the car. You could therefore assume that the odds of winning the car are 50-50! This is however a misconception! And if you play the game several times in a row, you will soon realise that you are twice more likely to win the car if you decide to switch your initial guess with the other door!

Not convinced? Try it… And if you want to fully understand the probabilities of this counter-intuitive puzzle you can check this page.

Frequency Analysis

In order to confirm these odds, we would like you to create a Python program that will simulate 100 games in a row, randomly positioning the two goats and the car behind the three doors every time. The program should then automatically and randomly select a door, reveal one door/goat and decide whether to switch doors or not. It should then determine whether the selected door leads to the car or the goat and keep a tally count of wins and losses.

At the end of the 100 attempts, the program should output the statistics as follows:

Python Code

We have only just started the code and thought about the key steps needed to complete this challenge. Your task is to complete the code below to produce a similar output (See statistics displayed above).

unlock-access

Solution...

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

Denary to Binary Conversion Algorithm

In this challenge, we are going to write al algorithm to convert a decimal (aka Denary) number between 0 and 255 into binary using 1 Byte (=8 bits).

Before attempting this challenge you may practise your denary to binary conversion:

Python Challenge


We are now going to use some Python code to implement al algorithm to convert a denary number into binary. To do so, you will need to complete the following 4 tasks.

Python Challenge - Task #1Task #2: Input ValidationTask #3: Writing a FunctionTask #4: Binary to Denary

Python Challenge: Task #1

We have started an algorithm which we would like you to complete to perform a full denary to binary conversion.

Your first challenge is to investigate the code below to see what it does and how it works. You will then need to complete this code to make sure that it outputs a fully Byte of data for any given number between 0 and 255.

The following trace table may help you investigate this code step by step:

 Line NumberdenarybinaryOUTPUT
3

Python Challenge: Task #2

Add some code to your code from task 1 to validate the input so that your code only accepts a number between 0 and 255. You can find out more about different validation techniques below and select the validation technique that is most relevant to this task:

Validation Techniques:


Input Validation: Presence Check

name = input("Enter your name:").strip() 

if name=="":
    print("Empty name!")
else:
    print("Thank you!")

Input Validation: Type Check – Integer?

number = input("Type a number:")

if number.isdigit():
    print("This is a number")
else:
    print("This is not a whole number")

Input Validation: Range Check

number = int(input("Type a number between 1 and 5:"))

if number>=1 and number<=5:
    print("Valid number")
else:
    print("Invalid number")

Input Validation: Lookup Check

drive = input("Can you drive?").lower()

if drive in ["yes","no"]:
    print("Valid answer")
else:
    print("Invalid answer")

Input Validation: Character Check

email = input("Type your e-mail address:")

if "@" in email:
    print("Valid e-mail address")
else:
    print("Invalid e-mail address")
postcode = input("Type your postocode:").upper()

if postcode[0] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and postcode[1] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and postcode[2] in "123456789":
    print("Valid postcode")
else:
    print("Invalid postcode")

Input Validation: Length Check

password = input("Type a password:")

if len(password)>=8:
    print("Valid password")
else:
    print("Invalid password")

Try Again! Using a While Loop:

name = input("Enter your name:")

while name=="":
    print("You must enter your name! Please try again!")
    name = input("Enter your name:")

print("Welcome " +  name)

Task #3: Writing a Function

Turn your code into a function called convertToBinary(). Your function will take a denary number as a parameter and return a binary string. You will then need to add some code to test your function.​

Task #4: Writing a Function

Create a new function called convertToDenary(). This new function will take a binary string as a parameter and return the matching denary value.


unlock-access

Solution...

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

Software Crosswords

A computer system consists of both hardware (the physical components of the computer) and software: the programs that run on this hardware.

There are three main categories of software:

  • Operating Systems: software that controls the computer hardware: The operating system can load programs into memory (e.g. RAM), instruct the CPU on which programs to run, interact with input, output and storage devices.
  • Utilities and Drivers: A range of specific software that can be used to help with the maintenance and security of the computer system
  • Application Software: A range of software used by the end-user to perform specific tasks.

Complete the following crossword to demonstrate your understanding of the three main types of computer software.
Computer Software CrosswordOpen Crossword Puzzle in a New Window
Computer Software CrosswordOpen Crossword Puzzle in a New Window

unlock-access

Solution...

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

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