More results...

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

Finding the Factors of… (LMC Challenge)

The aim of this challenge is to write a program using LMC to list all the factors of a given number.

The program will:

  • Ask the user to enter a positive number (e.g. 12)
  • Display all the factors of this number (e.g. 1,2,3,4,6,12)

High Level Flowchart


Here is the high-level flowchart for this algorithm. You can use it to first implement this algorithm using a high level language such as Python.
flowchart-factors-of-a-number

LMC Code


In order to implement this code in LMC you will first need to work out how to calculate the remainder (mod) of a division.

To complete this challenge you will need to use one of the following online LMC Simulators:

Test Plan


Here is a test plan to test your algorithm

Test # Type of Test Input Values Expected Output Actual Output
#1 Valid 12 1,2,3,4,6,12
#2 Valid 21 1,3,7,21
#3 Valid 48 1,2,3,4,6,8,12,16,24,48
#4 Valid 13 1,13

LMC Instruction Set


Note that in the following table “xx” refers to a memory address (aka mailbox) in the RAM. The online LMC simulator has 100 different mailboxes in the RAM ranging from 00 to 99.

Mnemonic Name Description Op Code
INP INPUT Retrieve user input and stores it in the accumulator. 901
OUT OUTPUT Output the value stored in the accumulator. 902
LDA LOAD Load the Accumulator with the contents of the memory address given. 5xx
STA STORE Store the value in the Accumulator in the memory address given. 3xx
ADD ADD Add the contents of the memory address to the Accumulator 1xx
SUB SUBTRACT Subtract the contents of the memory address from the Accumulator 2xx
BRP BRANCH IF POSITIVE Branch/Jump to the address given if the Accumulator is zero or positive. 8xx
BRZ BRANCH IF ZERO Branch/Jump to the address given if the Accumulator is zero. 7xx
BRA BRANCH ALWAYS Branch/Jump to the address given. 6xx
HLT HALT Stop the code 000
DAT DATA LOCATION Used to associate a label to a free memory address. An optional value can also be used to be stored at the memory address.
unlock-access

Solution...

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

The Fish and Chips Puzzle

To complete this puzzle, we first need to investigate the following lines of code:

a = "chips"
b = "fish"



print(a + " and " + b)

What would be the output of this code if you executed it?

Your challenge:


Complete lines 3,4 and 5, so that line 6 outputs “fish and chips”. You must comply with the following rules:

  • You are only allowed to use 4 keys on your keyboard: a, b, c and =. You can use these keys as many times as necessary.
  • You are not allowed to change lines 1,2 or 6.

Python Code

Trace Table

A trace table can be used to follow the steps of this algorithm one line of code at a time. This will help evaluate the impact of each steps on the different variables used in the code and on the predicted output of the program.

Complete the trace table below using your amended code to see if it produces the required output!

 Line NumberabcOUTPUT
1“Chips”
2“Fish”
3
4
5
6

unlock-access

Solution...

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

Cryptography Challenge

Cryptography, or cryptology is the practice and study of techniques for secure communication. Cryptography relies on using more or less complex encryption algorithms to encode a readable message (plaintext) into a collection of characters (ciphertext) that is hard to decipher (decode).

For this challenge, we are giving you a piece of Python code used to encrypt a message.

Your first task is to reverse-engineer this code to understand how this encryption algorithm works. Then, your challenge consists of writing a new function called decrypt(), that takes two parameters (a ciphertext and a key) and returns the plaintext corresponding to the given ciphertext.

Decryption Table..

Using your new decrypt() function, decrypt the following messages:

# Ciphertext Key Plaintext?
#1 YFwoJeELOvlDVrOlNBDConouLwhdCC mkIjsYeKsuaGsDbSRJymLJVOaYNQRrgKBSifPOdnCbUleWCbf 4
#2 HNABntvVepMaQSNHyKxQTXZf HVbQXcqJSXfswOAuRBzpefOdfBeylimeqDHDlFc 7
#3 PqKgakYBpfzveAHVrrUgbzpkaMWUcskukxac QfsWpFSrTrwiaQRtSsXesGlrBqv 3
#4 HXelrEed fCxojmVersu Gtehvee NSluGnJ 1
#5 PHcRrveeRUmDnfqMFAnBJvvwyzSDrj tqXhrLRXIegaDLwdInIGCvqelcjzU 5
unlock-access

Solution...

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

Back to the Future – Time Machine


In this Python challenge, we are going to investigate how to manipulate dates in Python using the datetime library.

The aim of this challenge is to write a piece of code to control the Time Machine (aka Flux Capacitor) found in the De Lorean Time Machine used in the Back to the Future trilogy.

The DeLorean time machine is a time travel device made by retrofitting a DMC DeLorean vehicle with a flux capacitor. The car requires 1.21 gigawatts of power and needs to travel 88 miles per hour to initiate time travel.

Time Machine (Flux Capacitor) Requirements

The python code used to control the time machine will:

    Display the current date (today),
    Display the day of the week of the current date,
    Ask the user to input a number representing the number of days for their time travel:

      A positive number to time travel in the future.
      A negative number to time travel in the past.

    Workout the end date by adding the number of days to time travel to the current date,
    Display the end date and the day of the week for this end date.

Python Code

Here is the Python code for our time machine!

Your Challenge

Write a Python script to work out the number of days between a specific date and today’s date.

For instance, if you would like to travel to the the Moon Landing Day: 16 Jul 1969. How many days would you need to travel back in time?

Your script will be very useful to configure the De Lorean time machine!

Your script should:

    Display the current date (today),
    Display the day of the week of the current date,
    Ask the user to enter a date in the DD/MM/YYYY format,
    Convert the user entry into a date,
    Calculate the difference in days between the current date and today’s date

      This difference should be a negative number of days of the input date is in the past.
      This difference should be a positive number of days of the input date is in the future.
  • Output the number of days between the two dates.

To test if your script is working, you can then input the resulting number of days in the DeLorean Time Machine above script and see if the resulting end date matches your input.

unlock-access

Solution...

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

Cumulative Elevation Gain Calculator


In mountaineering, running or cycling the cumulative elevation gain (aka total ascent) refers to the sum of every gain in elevation throughout an entire trip.

Note that when calculating this elevation gain, elevation losses are not counted in this measure.

When evaluating the difficulty of a hike, you should consider both the total distance of the hike as well as its cumulative elevation gain. Effectively, hiking 10 kilometres on flat land is significantly easier than hiking up and down a series of high peaks over the same distance.

In this challenge, we are going to write a Python script to help a hiker plan their journey by estimating the cumulative elevation gain of their planned hike.

Your Python script will need to:

  • Ask the user to enter the altitude of the starting point of the trip,
  • For each peak or pit on the planned journey, ask the user to enter the altitude of the peak/or peat,
  • Automatically add-up all the corresponding elevation gains (and ignore elevation losses!)
  • Output the cumulative elevation gain of the planned hike!

Python Challenge

Your challenge is to complete the Python code below…

Test Plan

Test # Input Values Expected Output Actual Output
#1 Starting Altitude: 1800m
1st Peak: 2100m
1st Pit: 1950m
2nd Peak: 2240m
Ending Altitude: 1800m
Cumulative Elevation Gain: 590m
#2 Starting Altitude: 1500m
1st Peak: 1850m
1st Pit: 1800m
2nd Peak: 2100m
2nd Pit: 1900m
3rd Peak: 2400m (End of Trek)
Cumulative Elevation Gain: 1150m
#3
unlock-access

Solution...

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

Maths Fraction Hack Algorithm

In this challenge we are going to use an easy hack to quickly compare two fractions without having to calculate their decimal value.

For instance, can you quickly tell which of the following two fractions is bigger?

Fraction Hack: The Butterfly method!

Here is our quick approach to compare two fractions. It is called the butterfly method and is based on performing a cross-multiplication as follows:

The butterfly method is used to calculate the cross-products of our two fractions. By comparing these cross-products we can then deduct how both fractions compare:

Python Task

Your task is to write a Python program that will:

  1. Ask the user for to enter four values: the numerators and denominators of two fractions.
  2. Use the butterfly method to calculate and compare the cross products of these two fractions.
  3. Compare the cross products to decide which fraction is bigger and output a clear message on screen.
  4. Calculate and output the decimal values of both fractions to help the user confirm the outcome of the Butterfly method.

Python Code

Test Plan

Test # Input Values Expected Output Actual Output
#1 7/10 and 5/8 7/10 > 5/8
#2 7/10 and 9/12 7/10 < 9/12
#3 7/10 and 21/30 7/10 = 21/30
#4 7/10 and 18/25 7/10 < 18/25
unlock-access

Solution...

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

The Mesh Network Puzzle

The mesh network puzzle consists of creating a partial mesh network that consists of:

  • Three workstations (client computers)
  • Three servers: a file server, an e-mail server and a web server.
    • Network Requirements

      Each client computer will need to be connected to all three servers using a partial mesh topology. The direct connections between a workstation and a server will be done using Ethernet cables.

      The constraint for this puzzle is that you are not allowed to cross over Ethernet cables!!!

      Here is our first attempt at solving this puzzle! in this attempt, you can see that we cannot connect the third workstation to the file server without crossing over an ethernet cable!

      Your Turn

      Grab a piece of paper and draw three workstations and three servers. Try to connect them following the requirements for this network.

      Alternatively, you can draw your network topology on this online whiteboard:

Solved Challenges

Solved Challenges (for members)

unlock-access

Solutions…

The solutions/code listings for these challenges are available to full members!
Find out how to become a member:
➤ Members’ Area

 
Return to Main Index

Bouncing Algorithm in a platform game

In this blog post we will investigate how to implement a bouncing algorithm used either in a platform game when the main sprite collides with a platform or in a breakout game when the ball bounce against a brick.

bouncing-platform-vs-breakout-game

(x,y) coordinates and velocity vector

In a frame based game, each sprite can be positioned on the screen based on its (x,y) coordinates. Each sprite can also be allocated a velocity vector. The velocity vector consists of two values (Vx, Vy) which represents the variation in pixels of the (x,y) coordinates of the sprite between two frames.

sprites-velocity-vector

Collision Detection

A collision occurs when two sprites are overlapping. Different algorithms can be used to detect such collisions. When creating a game with a library such as the Pygame library, you can re-use built-in collision detection algorithms without the need to implement these yourself.
sprites-collision

A collision will impact the velocity vectors of the sprites involved in the collision. In a platform game or breakout game, we can assume that the platform or the brick will remain static. However, the collision will impact the velocity vector of the main character or the bouncing ball. Note that in a pool game the collision between two balls would impact the velocity vectors of both sprites involved in the collision!

sprites-collision-velocity-vector

The change in direction will depends on which edge of the platform/brick is being hit first and on the initial direction of the sprite when it collides with the platform.

Let’s investigate one approach that could be used in both our games:

Implementing a Bouncing Algorithm

This approach consists of considering 8 possible different collisions and their impact on the velocity vector of the bouncing sprite.
bouncing-algorithm-8-scenarios

So, to implement an effective bouncing algorithm of a sprite against this platform, we must first identify the position of the sprite, relatively to the platform to distinguish the 8 possible areas. In the case of a rectangular platform, we can use the following comparisons between the (x,y) coordinates of the centre of our sprite with the top, right, bottom, left coordinates of our platform.
bouncing-algorithm-8-zones

The following pseudocode demonstrates how the bouncing algorithm can be implemented. Though it only covers the first three scenarios, you should be able to complete this algorithm further to cater for all 8 scenarios.
bouncing-algorithm-pseudocode

Landing on a platform

Note that the above pseudocode is used to make our sprite bounce against the platform which would be suitable for the breakout game and in most cases for a platform game. However, with a platform game. When the sprite lands on a platform (case 2 in the above diagram/pseudocode) we may not want the sprite to bounce back but instead we want the sprite to remain on top of the platform. In this case the pseudocode for this scenario would be as follows:
landing-on-a-platform

Tagged with:

Egg Code Stamp Decoder

Did you know that in the UK (and also in most European countries), the eggs you buy in a shop must be stamped with a code that can help you find out more about how and where your eggs were produced. This code is helpful to distinguish organic and free range eggs from eggs from more industrial production (e.g. barn or caged hen eggs).

Here is how the code works:
egg-code-stamp

Python Challenge

For this challenge you will need to write a Python script that:

  • Takes one input from the end-user: the code as it appear on a stamped egg. (Just the code, not the Best Before Date)
  • Use this code to output the farming method this egg originated from: (Organic, Free range, Barn or Cage)
  • Output the country of Origin: e.g.:
    • UK: United Kingdom
    • NL: Netherlands
    • FR: France
    • BE: Belgium
    • DE: Germany
    • ES: Spain
  • Output the farm/producer ID

Python Code

Complete the code below…

Test Plan

Test # Input Value Expected Output Actual Output
#1 1UK54321 Free Range Egg
Country of Origin: United Kingdom
Farm Id: 54321
#1 0NL6789 Organic Egg
Country of Origin: Nethelands
Farm Id: 6789
#1 3ES02468 Barn Egg
Country of Origin: Spain
Farm Id: 02468

Extension Task #1: Defensive Design

Update your code to automatically reject any invalid code:

  • A valid code contains at least 7 alphanumerical characters,
  • A valid code should start with a number digit between 0 and 3.

Extension Task #2: Country Codes

For our code to be complete, we need to recognise all the possible two-letter country codes. We have stored the full list of country codes in the following CSV file.


TextFile
Country-Codes.txt


Your task is to update your program for your code to automatically lookup for a country code using this CSV file.

unlock-access

Solution...

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


Tagged with: