More results...

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

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:

The World in 2050

Did you know that the world population increased from 1 billion in 1800 to around 8 billion today. And it’s still growing, even though the growth rate has declined from 2% per year around 50 years ago to approximatively 1% per year nowadays.

The aim of this challenge is going to use a Python script to estimate the growth of the world population over the next decades and to predict in which year, will the world population reach 10 billion.

We will base our projections using a static growth rate of 1% per year. (In reality, currently this growth rate is declining slightly every year). We will also start our projections using an estimate of the world population of 7,850,000,000 in 2022.

Step 1: Estimating next year’s population

Considering a 1% population growth per year, we can use the following formula to estimate next year’s population:

next year population = current population x 1.01

So we can implement this formula using Python:

year = 2022
population = 7850000000

year = year + 1
population = population * 1.01

print("In " + str(year) + ", the world population will be " + str(round(population,0)))

Step 2: Using iteration…


Let’s use an infinite loop to predict the growth of the world population in the coming years.
In Python we can implement an infinite loop using a while True: instruction.

To see the impact of our loop, we will pause for 1 second for each iteration. We will do so using the sleep() function from the time library.

import time
year = 2022
population = 7850000000

while True:
   time.sleep(1)
   year = year + 1
   population = population * 1.01

   print("In " + str(year) + ", the world population will be " + str(round(population,0)))

Step 3: Stopping when the population reach 10 billion…

Instead of running an infinite loop, we will run a loop that stops iterating as soon as the world population reaches or exceeds 10 billion.

We will use a condition in our while loop as follows:
while population<10000000000:

import time
year = 2022
population = 7850000000

while population<10000000000:
   time.sleep(1)
   year = year + 1
   population = population * 1.01

   print("In " + str(year) + ", the world population will be " + str(round(population,0))

Only showing the final result…

As the aim of this challenge was to find out in which year the world population will reach 10 billion, we do not need to output the world population for every single year. By unindenting our output (print instruction), we are taking this instruction away from the loop. So this instruction will only run once, after the while loop. We can also remove our pause (sleep) instruction to produce a response without delay.

year = 2022
population = 7850000000

while population<10000000000:
   year = year + 1
   population = population *1.01

print("In " + str(year) + ", the world population will be " + str(population))

Your turn…

Extension Task 1: The World in 2050

Tweak the code provided above so that instead of stopping when the population reaches 10 billion, the code (loop) stops when the year reaches 2050, in order to just output the world population in 2050.

Extension Task 2: The World and You!

Tweak this code, so that the program first asks for the end-user to enter their age.
Then the program should output the projection of both the world population and of the end-user’s age over the next 50 years. For instance, for an end-user who is eighteen in 2022, the output of your program should look like this:

    “In 2023, the world population will be 7928500000 and you will be 19 years old.”
    “In 2024, the world population will be 8007785000 and you will be 20 years old.”
    “In 2025, the world population will be 8087862850 and you will be 21 years old.”
    …and so on.

Extension Task 3: How many more inhabitants in 2050?

Adapt your code, for the program to calculate and output how many more inhabitants there will be on planet Earth, in 2050, compared to 2022.

unlock-access

Solution...

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

Light Bulb Energy Rating Calculator

Replacing a light bulb may not be as straight forward as it used to be. Nowadays there are many different types of light bulbs to choose from, including incandescent bulbs, halogen bulbs, fluorescent bulbs and so many different types of LED lights.

There are many criteria to consider when selecting a light bulb including:

  • The amount of light (aka luminous flux) the bulb provides, expressed in lumens (lm)
  • The power consumption over 1000 hours expressed in kW/1000h
  • The energy rating of the light bulb given as a rating between A and G

Energy Rating Ratio

The energy rating (aka Energy Efficiency class) of a light bulb is used to give an indication of how efficient / eco-friendly a light bulb is.

To workout the energy rating of a light bulb, we first need to calculate its lumens to watt efficiency ratio based on the following formula:

We can then use this ratio to determine the energy rating of the bulb using the following table:

Energy Rating Efficiency Ratio
210 or above
185 or above
160 or above
135 or above
110 or above
85 or above
Below 85

Python Challenge

Your task consists of writing a Python program that asks the user to enter two values:

  • The light output (luminous flux) of a light bulb (in lumens, lm)
  • The power consumption of the light bulb over 1000h (in kW/1000h)

Your program should then calculate the efficiency ratio of the light bulb to then output its energy rating as a label from A to G.

Python Code

You should complete your code below:

Test Plan

Once your code is complete, make sure it is working as expected by completing the following test plan:

Test # Input Values Expected Output Actual Output
#1 Light Output: 1600lm
Power Consumption: 8kW/1000h
Energy Rating: B
#2 Light Output: 1800lm
Power Consumption: 5kW/1000h
Energy Rating: A
#3 Light Output: 840lm
Power Consumption: 4kW/1000h
Energy Rating: A
#4 Light Output: 1100lm
Power Consumption: 12kW/1000h
Energy Rating: F
unlock-access

Solution...

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

Digit Sum Algorithm

For this challenge, we are going to write a function to calculate the digit sum of a given number.

The digit sum of a number corresponds to the sum of all the digits of this number.

For instance the digit sum of 365 is 3 + 6 + 5 = 14.

Here is the flowchart for our digitSum() function, that takes one parameter called number (any given number: e.g. 365) and returns the digit sum of this number (e.g. 14)

In pseudocode, or on a flowchart the DIV operator represent the quotient of a whole division: e.g. 365 DIV 10 = 36 whereas the MOD operator represents the remainder: e.g. 365 MOD 10 = 5.

Note that, when using Python, the DIV operator is // (e.g. 365 // 10 = 36) and the MOD operator is % (e.g. 365 % 10 = 5)

Trace Table

To understand how this algorithm works, you will first need to trace it when the parameter is set to the value 365. To trace do so, you will have to complete the trace table below. (Note that we have labelled our flowchart with line numbers to help you complete the table below).

 Line Numbernumbersumnumber>0?lastDigitReturned Value
1365
20
3True

Python Code

Your next step is to implement this algorithm using Python code. After coding the digitSum() function using the above flowchart, you will also need to implement a short algorithm to test your function. You can use the flowchart below to do so:

Use the following Python trinket to complete your code online:

Test Plan

Once your code for both your digitSum() function and your short algorithm to test your function have been implemented, you will need to test your code using the following test plan:

Test # Input Values Expected Output Actual Output
#1 365 14
#2 24 6
#3 4096 19
#4 123456 21
#5 7 7
unlock-access

Solution...

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

The Uppercase Challenge

The aim of this challenge is to rewrite the upper() function that is used in Python to convert the case of a string to uppercase.

This is how the upper() function works in Python:

string = "Hello world!"
upString = string.upper()
print(upString)

For this challenge we will write a function called uppercase() that takes a string as a parameter and returns the uppercase version of this string. However, to complete this challenge we are not allowed to use the pre-defined upper() or lower() Python functions!

Our Python function will need to:

  1. Access each character of the given string
  2. Find out if the character is a lowercase letter of the alphabet
  3. If so, convert this character to its uppercase equivalent. (We will do so using the ASCII code!)
  4. Append the character to a new string
  5. Return the new string once all character have been checked.

ASCII Code

Each character that you can use on your keyboard has a unique ASCII value, a number between 0 and 255. This includes the 26 letters of the lowercase alphabet, the 26 letters of the uppercase alphabet, the number digits 0 to 9 and all the punctuation signs such as !,?.#, etc. Even the space bar has a unique ASCII value: 32.

Here are the ASCII values of the lowercase alphabet:

Character a b c d e x y z
ASCII 97 98 99 100 101 120 121 122

And below are the ASCII values of the uppercase alphabet:

Character A B C D E X Y Z
ASCII 65 66 67 68 69 88 89 90

So, if we have the ASCII value of a lowercase character, we can retrieve the ASCII value of its matching uppercase character by taking away 32 from the ASCII value of the lowercase character.

For instance:

(a) 97 – 32 = 65 (A)

And…

(z) 122 – 32 = 90 (Z)

Python Code and ASCII Code

In Python, you can use the ord() and chr() functions to convert a character into its ASCII value and vice-versa.

For instance, the ord() function is used get the ASCII value of any given character:

character = "A"
ascii = ord(character)
print(ascii)  #Output 65

The chr() function returns the character for any given ASCII value (number between 0 and 255).

ascii = 65
character = chr(ascii)
print(character) #Output A

Also, to find if a character is a character from the lowercase alphabet, all we need to do is check that its ASCII value is between 97 and 122.

character = input("Enter any character!")
ascii = ord(character)
if ascii>=97 and ascii<=122:
   print("This is a lowercase character!")
else:
   print("This is not a lowercase character!")

Finally, remember that in Python, you can easily access each character of a string using a for loop:

string = "Hello world!"
for character in string:
    print(character)

Alternative method:

string = "Hello world!"
for i range in range(0,len(string)):
    print(string[i])

Your Turn…

It is now your turn to code your own uppercase() function in Python, without using the existing upper() or lower() functions!

Remember, your function will take a string as a parameter and will need to:

  1. Access each character of the given string
  2. Find out if the character is a lowercase letter of the alphabet
  3. If so, convert this character to its uppercase equivalent. (We will do so using the ASCII code!)
  4. Append the character to a new string
  5. Return the new string once all character have been checked.

We have started this function for you and you will now need to complete the code to implement the above 5 steps!

unlock-access

Solution...

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

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