More results...

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

Mnemonic Phrase Validator

Welcome to the Mnemonic Phrase Validator Challenge! This Python challenge is designed to help you practise your coding skills while creating a useful tool for validating mnemonic phrases.

Mnemonic Phrase?

Mnemonic phrases are often used to remember specific sequences or information, such as the order of the planets in the solar system.

The following Mnemonic phrase makes it easier to remember the order of the planets as each word in this sentence starts with the letter corresponding to a planet in the solar system, matching their position from the Sun: from Mercury, closest planet to the Sun to Pluto, furthest planet to the Sun.

My Very Easy Method Just Speeds Up Naming Planets.

Mnemonic Phrase

As you can see this phrase contains all the planets in order: My (Mercury) Very (Venus) Easy (Earth) Method (Mars) Just (Jupiter) Speeds (Saturn) Up (Uranus) Naming (Neptune) Planets (Pluto – dwarf planet)

Python Challenge

For this challenge, you are going to write a Python program based on the Input/Process/Output model:

  1. Input: Accept a phrase from the user.
  2. Process: Define and implement validation rules to check the phrase.
  3. Output: Provide feedback to the user indicating whether the phrase is valid or not.

Validation Checks

To validate a mnemonic phrase we will use the following validation rules:

  • Length: The phrase should be between 10 and 50 characters long.
  • Unique Words: Each word in the phrase should be unique.
  • Alphabetical Characters Only: The phrase should only contain alphabetic characters and spaces.
  • Sequence Matching: Each word must start with the letter corresponding to the sequence we want to learn, in the same order. For example, if remembering the order of the planets, the phrase “My Very Easy Method Just Speeds Up Naming Planets” is valid because each word starts with the first letter of a planet’s name in order.

Let’s see how we can implement these four types of validation checks in Python:

Length CheckUnique WordsAlphabetical Characters OnlySequence Matching
Our first check consists of checking that our mnemonic phrase is long enough but not too long, in other words a valid mnemonic phrase should be between 10 and 100 characters long.

In Python, we can use the len() function to find out the number of characters in a string.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
if len(phrase)<10 or len(phrase)>100:
      print("Invalid: Phrase length should be between 10 and 100 characters.")
      return False
Our next check consists of checking that the phrase given only include unique words. To implement this check in Python we will first need a list of all the words contained in our phrase. We can create such a list of words using the split() function using the space character to split our phrase into separated words.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
words = phrase.split()

We can then use the set() function in python which returns a set of unique values from a given list by removing duplicate values. If the resulting set contains as many words as the initial list of words, we can deduct that all the words in the words list must have been unique.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
# Check for unique words
words = phrase.split()
if len(words) != len(set(words)):
   print("Invalid: Each word should be unique.")
   return False
To check if each word of our phrase only contains alphabetical characters we can use the isalpha() function that returns True if a given string value only contains characters from the alphabet (lowercase or uppercase).

To check the whole sentence, we will first create a list of words as we did in the previous check, using the split() function. We will then iterate through this list of words, to check one word at a time.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
 # Check for special characters
words = phrase.split()

for i in range(0,len(words)):
   if not words[i].isalpha():
      print("Invalid: Phrase should only contain alphabetic characters and spaces.")
      break #No need to check other words
To check that each word from the phrase starts with the same letter as each word in the given sequence we will loop through our list of words and extract the first characters (at position 0) from the list of words and from the given sequence.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
sequence = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune","Pluto"]
valid = True
# Check sequence matching
for i in range(0,len(words)):
   if not words[i][0] == sequence[i][0]:
      print("Invalid: Each word must start with the corresponding letter in the sequence.")
      valid=False
      break #No need to check other words
if valid==True:
   print("Valid Sequence Matching!")

Python Code

Your task is to use the techniques mentioned in the four tabs above to complete this Mnemonic Phrase Validator challenge.

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 Vigenère Cipher – Python Challenge

In the world of cryptography, the Vigenère Cipher represents a significant milestone in the evolution of encryption techniques. To fully appreciate its significance, let’s take a step back and explore its roots, starting with the Caesar Cipher.

The Caesar Cipher: A Historical Foundation

The Caesar Cipher, named after Julius Caesar who used it to protect sensitive information, is one of the earliest known encryption methods. It operates by shifting each letter in the plaintext by a fixed number of positions down the alphabet. For example, with a shift of 3, ‘A’ becomes ‘D’, ‘B’ becomes ‘E’, and so on. With this encryption technique the key represents the number used for shifting letters in the alphabet. (e.g. in our example the key is 3).

While simple and effective for its time, the Caesar Cipher is easy to break. Effectively, with the Caesar Cipher there are only 26 possible keys, so it’s easy to try them all to decode an encrypted message. The Caesar Cipher is also vulnerable to frequency analysis, where the frequency of letters in the ciphertext is analysed to deduce the original message. This limitation paved the way for more complex encryption methods, including the Vigenère Cipher.

The Vigenère Cipher: Enhancing Security

The Vigenère Cipher, invented by Blaise de Vigenère in the 16th century, builds upon the principles of the Caesar Cipher but introduces a significant enhancement: it uses a keyword to determine the shift for each letter in the plaintext. This means that instead of a single shift value, the Vigenère Cipher employs a different shift for each letter of the message to encrypt, making it much harder to crack using a frequency analysis. It also means that any keyword (or sequence of letters) can be used as the key which exponentially increases the number of possible unique keys available and making it virtually impossible for a human being to try all the possible keys one at a time.

How the Vigenère Cipher Works

Step 1: Choose the key: Decide on a keyword that will be used to encrypt the message. For example, let’s use the keyword “CRYPTO”

Step 2: Align the key with the plaintext: Align the keyword along the length of the plaintext. As the plaintext message will most likely be longer than the key, you may have to repeat the key. For instance ff the plaintext is “VIGENERECIPHER” and the KEY is “CRYPTO” the alignment would look like this:

Plaintext: V I G E N E R E C I P H E R
Keyword:   C R Y P T O C R Y P T O C R

Step 3: Apply Caesar Shift Encryption: Shift each letter in the plaintext by the position in the alphabet of the corresponding letter of the key. For instance, ‘V’ is shifted by ‘2’ as ‘C’ is at position 2 in the alphabet (we start with position 0 for ‘A’) so ‘C’ becomes ‘X’, whereas ‘I’ is shifted by 17 as ‘R’ is at position 17 in the alphabet.

Python Challenge: Implementing the Vigenère Cipher

Now that you have a basic understanding of both the Caesar Cipher and the Vigenère Cipher, it’s time to put your programming skills to the test! Below is a Python challenge to implement both ciphers.

Tips:
Convert the plaintext and keyword to uppercase to handle case sensitivity.
Use the ASCII values of the letters to perform the shifts.
When shifting a letter, if the resulting letter is after Z, it should go back to the start of the alphabet. (e.g. ‘X’ shifted by 3 becomes ‘A’)
For the Vigenère Cipher, ensure the key repeats to match the length of the plaintext.

Getting Started: Caesar Cipher

The following code will help you identify the main steps of a Caesar Cipher algorithm:

plaintext="CAESAR"
key = 3
cipher = ""
# Parse through the plaintext, one character at a time
for i in range(0, len(plaintext)):
   #Retrieve the ASCII value for the current character
   ascii = ord(plaintext[i])
   #Only encrypt letters from the alphabet, from A=65 to Z=90
   if ascii>=65 and ascii<=90: 
      # Encrypt the letter by shifting the ASCII value by the key
      ascii = ascii + key
      # If the new encrypted letter is after Z, it goes back to A
      if ascii > 90:
         ascii = ascii - 26
   cipher = cipher + chr(ascii)

Extension Task:

Extend your implementation to include two decryption functions that take the encrypted text and the key as inputs and return the original plaintext.

unlock-access

Solution...

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

Famous Shipwrecks Explorer – Python Challenge

With this challenge, we will embark on a virtual voyage across the seven seas to uncover the secrets hidden underwater. For centuries, shipwrecks have captivated the imagination of explorers and historians alike, each sunken vessel holding tales of bravery, tragedy, and discovery. From legendary ships like the Titanic to lesser-known but equally fascinating wrecks, these underwater treasures offer a glimpse into our maritime past.

The Thrill of Shipwreck Hunting

Shipwreck hunters are modern-day treasure seekers, armed with advanced technology and an insatiable curiosity. They scour the oceans, lakes, and seas, searching for the remnants of vessels lost to time. Each discovery is a testament to human ingenuity and resilience, a tangible link to our shared history.

Imagine the thrill of locating a long-lost ship, its hull encrusted with barnacles and coral, resting silently on the ocean floor. The stories these wrecks could tell – of storms weathered, battles fought, and voyages cut short. Now, with the power of Python, you can join the ranks of these intrepid explorers and unveil the mysteries of the deep from the comfort of your own computer.

Your Mission

In this challenge, you will create a Python program that allows users to select or input the name of a famous shipwreck. Your program will then dive into a CSV file containing data on renowned shipwrecks, performing a linear search to extract the relevant information. Once the data is retrieved, the program will display the exact location of the shipwreck on a world map, giving users a visual representation of these historic sites.

Learning Objectives

  • Reading data from a CSV file using Python
  • Performing a linear search through a list of data
  • Extracting and displaying specific information
  • Using external libraries to visualize data on a world map

CSV File

A CSV (comma-separated values) file is a plain text file that stores data in a table format. Each line of the file contain a record about a specific entity, in this case a famous shipwreck. On each line, each piece of data (field/column) is separated using a specific characters (e.g. a comma)

For this challeneg, we will be using a CSV file named famous_shipwrecks.csv containing information about several shipwrecks. The file has the following columns:

Ship Name, Year Sank , Longitude , Latitude , Depth (meters) , Sea/Ocean , Year Discovered , Country of Origin , Type of Vessel

You will find the CSV file on a separate tab of the IDE provided below.

Extracting data from a CSV file


You can easily scan through the content of a CSV file one line at a time and extract indvidula field values using the split() function in Python. For instance you can try the following code to scan through the famous_shipwrecks.csv file.

file = open("famous_shipwrecks.csv","r")

for line in file:
   data = line.split(",")
   print(data[0] + " - " + data[1] + " - " + data[2] + " - " + data[3])
  
file.close()

By tweaking the above code slightly, we can perform a linear search on the first field (ship name):

file = open("famous_shipwrecks.csv","r")

for line in file:
   data = line.split(",")
   if data[0]=="Titanic":
      print(data[0] + " - " + data[1] + " - " + data[2] + " - " + data[3])
  
file.close()

Python Challenge

Write a Python program that:

    Asks the user to enter the name of a shipwreck.
    Opens and reads the famous_shipwrecks.csv file.
    Performs a linear search through each line of the file to find the shipwreck.
    If found, displays the following information:

    • Name of the shipwreck
    • Latitude and Longitude
    • Depth (in meters)
    • Name of the Sea/Ocean where it was found
    • Year it sank
    • Year it was discovered

    Use the provided code snippet to display the shipwreck location on a world map.
    If the shipwreck is not found, display an appropriate message.

Python Code

We have started the code. You can see who this code is used to plot a specific location (longitude/latitude) on a world map.

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 Pizzaiolo’s Pizza Sizing Challenge

Let’s start this coding challenge with a simple question: assuming your are organising a pizza party and would like to make sure there will be enough pizza for your guests, would you rather order a single 18-inch pizza or order 2 smaller 12-inch pizzas?

The answer might surprise you but a 18″ pizza would have more pizza than two 12″ pizzas! To verify this statement let’s calculate the actual areas of our pizzas:

For this challenge, all areas are expressed in square inches: in2

As we can see 81π > 72π hence an 18″ pizza will give you more pizza than two 12″ pizzas!

The Pizzaiolo’s Challenge

For this coding challenge, we will use a Python script to help a pizzaiolo determine the perfect size for their pizzas. Our pizzaiolo offers pizzas in three sizes: small, medium, and large. The medium-sized pizza has a diameter of 12 inches.

Our pizzaiolo would like to find out what the size (diameter) of a large pizza should be to to ensure that the large pizza is exactly equivalent in area to two medium-sized pizzas.

So, let’s break down the challenge and provide you with the tools you need to solve it.

Aim of this Challenge:
The challenge is to write a Python script that calculates the diameter of a large pizza such that its area is exactly equivalent to the combined area of two medium-sized 12″ pizzas.

Understanding the Problem
To solve this problem, we need to understand the relationship between the diameter and the area of a circle (which is the shape of our pizzas). The formula for the area of a circle with a diameter D is:

Given that the diameter of a medium pizza is 12 inches, we can calculate its area as follows:

Since we want the large pizza to have the same area as two medium pizzas, the area of the large pizza should be:

Solving the Challenge
There are two main approaches to solve this challenge. We could either use an iterative trial and error approach or we could use an exact algebraic calculation.

1: Iterative trial and error approach2: Algebraic calculation

1. Using an Iterative Trial and Error Approach:

This approach involves guessing the diameter of the large pizza, calculating its area, and adjusting the guess until the area matches (72π).

Here’s a Python script that uses the iterative trial and error approach:

2. Using an Algebraic Calculation:

This approach involves using the area formula directly to solve for the diameter of the large pizza.

Here’s a Python script that uses the algebraic approach:

Your Turn: Calculating the size of a Small Pizza

Now that we’ve determined the diameter of the large pizza, let’s extend the challenge to find the diameter of the small pizza. The requirement is that three small pizzas should have the same area as two medium-sized pizzas.. Your task is to complete the code provided above, using either a trial and error approach or working out the exact algebraic formula to solve this challenge.

The Allotment Crop Planner (Python Challenge)

In this challenge, we will work with a JSON dataset containing detailed information about crops that can be grown in an allotment. The dataset includes, soil types, watering needs, and more.

Your task is to write a Python program that helps an allotment gardener by answering specific questions about what they can grow and when.

Learning Objectives

By completing this challenge you will improve your python skills and learn to:

  • Load a JSON dataset using the json module.
  • Use loops on lists and dictionaries data structures to filter crops based on user input.
  • Convert a user input (month, soil type, etc.) to a standard format to avoid case-sensitivity issues.

The JSON Dataset

Here is a sample of the dataset that your program will use:

{
  "allotment_crops": [
    {
      "name": "Carrot",
      "type": "Vegetable",
      "planting_season": ["March", "April", "May", "June", "July"],
      "harvest_season": ["June", "July", "August", "September", "October"],
      "soil_type": "Light, sandy, well-drained",
      "sunlight": "Full sun",
      "watering_needs": "Moderate",
      "container_friendly": true
    },
    {
      "name": "Tomato",
      "type": "Fruit",
      "planting_season": ["March", "April", "May"],
      "harvest_season": ["July", "August", "September"],
      "soil_type": "Rich, well-drained",
      "sunlight": "Full sun",
      "watering_needs": "Regular",
      "container_friendly": true
    }
  ]
}

(The full dataset is provided in a separate json file in the Python IDE below.)

Python Challenges

To complete this project, you will need to complete all 5 challenges listed in the tabs below:

Challenge 1: Crops to Plant This MonthChallenge 2: Crops to Harvest This MonthChallenge 3: Container-Friendly CropsChallenge 4: Best Crops for Your GardenChallenge 5: Interactive Crop Assistant

Challenge 1: Crops to Plant This Month

The aim of this first challenge is to write a Python function that asks the user for the current month and displays all the crops that can be planted in that month.

Example Input/Output:

Enter the current month: April
Crops you can plant in April:
- Carrot
- Tomato

Challenge 2: Crops to Harvest This Month

Reusing similar code to the code provided to solve challenge 1, write another function Python function that asks the user for the current month and displays all the crops that can be harvested in that month.
Example Input/Output:

Enter the current month: September
Crops you can harvest in September:
- Carrot
- Tomato

Challenge 3: Container-Friendly Crops

Some gardeners have limited space and need to grow crops in pots. Write a function that lists all crops that can be grown in containers.

Example Output:

Container-friendly crops:
- Carrot
- Tomato

Challenge 4: Best Crops for Your Garden

Modify your program to ask the user about their soil type and sunlight conditions and then recommend crops that match their garden environment.

Example Input/Output

Enter your soil type: Sandy
Enter your sunlight condition (Full sun/Partial shade): Full sun

Crops suitable for your garden:
- Carrot

Challenge 5: Interactive Crop Assistant

Enhance your program by allowing users to search for a specific crop and view detailed growing advice, including watering needs and best companion plants.

Example Input/Output

Enter a crop name: Tomato

Tomato (Fruit)
- Planting season: March - April - May
- Harvest season: July - August - September
- Soil type: Rich, well-drained
- Sunlight: Full sun
- Watering needs: Moderate
- Container-friendly: Yes

Python Code

Here is the full python code for this first challenge. Your task will be to re-use similar code to complete the remaining challenges described in the 5 tabs above.

unlock-access

Solution...

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

The Explorer’s Challenge: Naming New Species with Code

After months of adventure on the mysterious island of Xylogora, young explorer Mateo has finally returned home. His backpack is stuffed with notes, sketches, and a collection of breathtaking photos of creatures never seen before. From the feathered glimmerfox to the six-legged rippletoad, each animal was stranger and more exotic than the last.

But Mateo has a problem: Every great discovery needs a name, and he has dozens of new species waiting to be named and documented.

Pulling out his laptop, Mateo decides to create a naming algorithm using string-handling techniques. His plan is simple yet ingenious: take the names of existing animals, rearrange their letters, or combine parts of their names to create unique ones. For instance, the “Wolphin” might come from “Wolf” and “Dolphin”.

String Handling Techniques

To create his algorithm, Mateo will need to use the following string handling techniques:


  • LEFT: to extract characters at the beginning of a string,
  • RIGHT: to extract characters at the end of a string,
  • SUBSTR or MID: to extract a set number of characters at a given position in a string,
  • LENGTH: to find out the number of characters in a string,
  • String Concatenation: to join two or more strings together.

LEFTRIGHTSUBSTRString ConcatenationLENGTH
The LEFT() function is used to extract the first 5 characters of a string.

For instance:
LEFT(“WOLF”, 3) would return “WOL”.

The RIGHT() function is used to extract the last 5 characters of a string.

For instance:
RIGHT(“DOLPHIN”, 4) would return “PHIN”.

The SUBSTR() function is used to extract a set number of characters at a given position in a string. Note that in this case the first letter in a string is at position 0.

For instance:
SUBSTR(“PANDA”, 1, 3) would return “AND”.

String concatenation is a technique that uses the + operator to join two or more strings together.

For instance:
“WOL” + “PHIN” would return “WOLPHIN”.

The LENGTH() function is used to retrieve the number of characters in a string.

For instance:
LENGTH(“DOLPHIN”) would return 7.

Naming Unknown Species

Can you work out the name given to the following species?

Python Challenge

Can you help Mateo by writing a Python program that generates exotic animal names using string handling techniques? Your program will need to:

    Takes two (or more) animal names as inputs.
    Randomly combines parts of each name to create a new species name.
    Output the generated name.
    Let the user decide if they like the name or if the computer should have another go.

To do so you will need 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

Scheduling Algorithms – Python Challenge

Job Scheduling AlgorithmOne of the main purpose of the Operating System is to control the hardware and more specifically the CPU. The CPU performs all the jobs/processes requested by the different applications. A scheduler is a program of the Operating System that manages the amount of time that is allocated to each job that the CPU needs to process. To do so the scheduler keeps a list of all the jobs that need to be processed. This is called the job queue. The scheduler also uses a scheduling algorithm to determine in which order these jobs will be processed and the amount of processing time to allocate to each job.

The main job scheduling algorithms are:

  • FCFS: First Come First Served
  • Round Robin
  • Shortest Job First
  • Shortest Remaining Time First
  • Multilevel Feedback Queues

The type of algorithm used by an OS depends on the main functions and characteristics of the system and the typical workload and type of jobs the system will need to process. For instance the scheduler inside a networked printer, the scheduler of a personal tablet computer, the scheduler of a smart speaker and the scheduler of a high spec web-server may all use a different approach to managing their job queue!

Use the tabs below to investigate the characteristics, strengths and drawbacks of the main job scheduling algorithms

FCFSRound RobinShortest Job FirstShortest Remaining Time FirstMultilevel Feedback Queues

FCFS (First Come First Served):

Jobs are executed in the order they arrive. The first job to arrive is the first to be executed, and the process continues in this manner.

  • Pros: Simple to implement.
  • Cons: Can lead to long wait times, especially if a long job arrives before shorter ones (known as the “convoy effect”).

Typically a networked printer may use a First Come First Served approach to process each printing job in order they were received/added to the printer queue.

Round Robin (RR):

Each job gets a fixed time slice (quantum). If a job doesn’t finish within its time slice, it’s moved to the back of the queue, and the next job in line is given CPU time.

  • Pros: A fair approach that prevents any job from monopolising the CPU.
  • Cons: Performance can degrade if time slices are too short or too long.

Typically this can be used by multi-user systems such as web servers which have to deal with concurrent requests from many users and want to make sure that each user’s request is processed fairly.

Shortest Job First (SJF):

The job with the shortest burst time (estimated CPU time required) is executed first.

  • Pros: Minimises average waiting time.
  • Cons: Difficult to predict the exact burst time of a job, and can lead to starvation of longer jobs.

Shortest Remaining Time First (SRTF):

A preemptive version of SJF. The job with the shortest remaining time to completion is executed first. If a new job arrives with a shorter remaining time than the current job, the current job is preempted.

  • Pros: Reduces waiting time and responds dynamically to new jobs.
  • Cons: Can lead to frequent context switching and is complex to implement.
  • Cons: Difficult to predict the exact remaining time of a job, and can lead to starvation of longer jobs.

Multilevel Feedback Queues (MLFQ):

Jobs are placed in different priority queues. If a job doesn’t finish quickly enough, it is moved to a lower priority queue with longer time slices. Jobs that use too much CPU time may be demoted, while I/O-bound jobs can be promoted to higher-priority queues.

  • Pros: Adapts well to different types of jobs and improves overall system performance.
  • Cons: Complex to manage and implement.

Python Challenge

A scheduler is part of the Operating system. It would most likely have been programmed using low-level (assembly) language. However for the purpose of this task, we are going to use a Python program to create a high-level demo to show how some of the main scheduling algorithms would process a given job queue.

Python Code

We have started the code for you have implemented the First Come First Served algorithm (FCFS).
Your task is to use a similar approach to implement the following scheduling algorithms:
 First Come First Served algorithm (FCFS)
 Round Robin algorithm
 Shortest Remaining Time First algorithm

unlock-access

Solution...

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

Spot the logic error

Below are 10 different functions. The syntax for these functions is correct, however when testing these functions, you will notice that they do not produce the expected output: each of these functions contain a logic error.

Did you know?

To troubleshoot a piece of code to spot logic errors is called debugging! The reason why a logic error is also called a bug is because one of the first computer programs to not behave as expected was due to an actual moth that was stuck in the electronic components of the computer creating a short circuit. Once the computer scientists spotted this bug, they removed it and the computer program worked again. Since then spotting and removing a logic error in a piece of code is called debugging the code!

Debugging Task

Your task is to copy the code of the following 10 functions in the online IDE provided below to then spot and fix the given code. Make sure to use a range of test data to fully test your functions.

Code #1Code #2Code #3Code #4Code #5Code #6Code #7Code #8Code #9Code #10

Our first function is used to find out if a number is odd or even. For instance check_end_or_odd(5) should output the word “Odd” on the screen.


def check_even_or_odd(number):
    if number % 2 == 1:
        print("Even")
    else:
        print("Odd")
        
check_even_or_odd(5)

Our second function is used to return the largest (max) of 3 numbers.


def findMax(a, b, c):
    if a > b or a > c:
        return a
    elif b > c:
        return b
    else:
        return c
        
print(findMax(7, 3, 9))

This function finds out if a given numebr is a prime number or not.


def isPrime(n):
    for i in range(2, n):
        if n % i == 0:
            return True
    return False

print(isPrime(5))

This function is used to reverse a string so for instance the string 101Computing should become gnitupmoC101.


def reverse_string(text):
    reversed_string = ""
    for char in text:
        reversed_string = reversed_string + char
    return reversed_string

print(reverse_string("101Computing"))

This function counts the number of vowels in a given string. So for instance in the string “Adele” we have 3 vowels.


def countVowels(name):
    vowels = "aeiou"
    count = 0
    for char in name:
        if char in vowels:
            count += 1
    return count

print(countVowels("Adele"))

This function claculate the iterative sum of a number e.gg Iterative Sum of 5 is 1 + 2 + 3 + 4 + 5 = 15


def iterativeSum(n):
    sum = 0
    for i in range(1,n):
        sum = sum + i
    return sum

print("iterativeSum(5) = 5 + 4 + 3 + 2 + 1 = " + str(iterativeSum(5)))

This function calculates a factorial value of any given number. For instance: %5 = 5 x 4 x 3 x 2 x 1 = 120


def factorial(n):
    if n == 0:
       return 1 #because 0! is 1
    else:
       f = 0
       for i in range(1,n+1):
          f = f * i
       return f

print("5! = 5 x 4 x 3 x 2 x 1 = " + str(factorial(5)))

This function counts the number of occurrences of a given value within a given list.


def count_occurrences(list, target):
    count = 0
    for element in list:
        if element == target:
            count = +1
    return count

print(count_occurrences([5, 2, 3, 5, 5, 4, 2], 5))

This function takes a list as a parameter and return another lists by removing all duplicate values from the initial list.


def remove_duplicates(list):
    unique_items = []
    for item in list:
        if item not in unique_items:
            unique_items.append(item)
    return list

print(remove_duplicates([1, 2, 2, 1, 3, 3, 4, 5]))

Our last function is used to display a tic tac toe (aka noughts and crosses) grid on the screen as a 3 by 3 grid.


def printGrid(grid):
   print(" |---+---+---|")
   line = ""   
   for i in range(0,3):
      for j in range(0,3):
         line = line + " | " + tictactoe[i][j]
      print(line + " |")
      print(" |---+---+---|")

tictactoe = [["X","O","X"],["O","X","O"],["X","X","O"]]
printGrid(tictactoe)

Online Python IDE

Use this online Python IDE to test the above functions, spot the logic errors and fix the code!

unlock-access

Solution...

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

Chinese New Year Coding Challenge

Chinese New Year (新年) aka Spring Festival (春节), is one of the most important festivals in Chinese culture. It has been celebrated in China for thousands of years. People celebrate by decorating their interior in red using red couplets of Chinese poetry, lanterns and colourful flowers. The festival is also the opportunity for Chinese people around the world to prepare and enjoy a range of traditional food dishes and to celebrate by watching traditional dragons and lions dances.

Chinese Zodiac Signs

The Chinese New Year is based on the Lunar calendar and typically falls at the end of January or in February depending on the Moon cycle. Every year is associated with an animal corresponding to a Chinese Zodiac sign. There is a 12-year cycle with twelve zodiac signs in the following order:

Animal/Zodiac Sign Years
Dragon … 2000, 2012, 2024 …
Snake … 2001, 2013, 2025 …
Horse … 2002, 2014, 2026 …
Ram (Goat) … 2003, 2015, 2027 …
Monkey … 2004, 2016, 2028 …
Rooster … 2005, 2017, 2029 …
Dog … 2006, 2018, 2030 …
Pig … 2007, 2019, 2031 …
Rat … 2008, 2020, 2032 …
Ox … 2009, 2021, 2033 …
Tiger … 2010, 2022, 2034 …
Rabbit … 2011, 2023, 2035 …

So this year we will celebrate Chinese New Year on January 29th 2025 and the Chinese Zodiac sign / animal for 2025 is the Snake! Maybe a sign that you could dedicate this year to boosting your coding skills using Python 😉

Coding Challenge

For this challenge, you are going to write a Python program that will ask the user to enter the year of their date of birth. Your program will then inform the user of their Chinese Zodiac sign matching their date of birth.

Python Code

Complete the code below to solve this challenge.

Test Plan:

Complete the folowing test plan to check if your code is giving you the correct zodiac signs for he following years (using both past and future years):

Test # Input Values Expected Output Actual Output
#1 Year: 2007 Pig
#2 Year: 2021 Ox
#3 Year: 1998 Tiger
#4 Year: 1912 Rat
#5 Year: 1789 Rooster
#6 Year: 2050 Horse
#7 Year: 2100 Monkey

Extension Task 1:

With the year matching your date of Birth you can also work out what is your Chinese Zodiac element.

To do so you wil need to check the the last digit of your birth year. if this last digit is:

  • 0 or 1: Your element is Metal
  • 2 or 3: Your element is Water
  • 4 or 5: Your element is Wood
  • 6 or 7: Your element is Fire
  • 8 or 9: Your element is Earth

Your task is to tweak your Python code so that when the user enters a date, your program outputs both the Chinese Zodiac sign and the Chinese Zodiac element corresponding to the given year.

Extension Task 2:

Each Zodiac sign has specific attributes which can be used to describe the year to come.

We have stored these attributes using a dictionary:

animals = {"Dragon":"Charismatic, powerful, and ambitious, the Dragon is a symbol of strength and good fortune.",
           "Snake":"Wise, intuitive, and elegant, the Snake is calm and strategic, with a deep understanding of the world.",
           "Horse":"Energetic, free-spirited, and optimistic, the Horse loves adventure and pursues goals with enthusiasm.",
           "Ram":"Creative, gentle, and empathetic, the Goat seeks beauty and tranquillity, often expressing artistic talents.",
           "Monkey":"Intelligent, playful, and clever, the Monkey is resourceful and loves solving problems with wit and charm.",
           "Rooster":"Confident, honest, and hardworking, the Rooster is practical, ambitious, and detail-oriented.",
           "Dog":"Loyal, trustworthy, and protective, the Dog is compassionate and always stands up for what’s right.",
           "Pig":"Generous, kind-hearted, and sincere, the Pig is known for its honesty, hard work, and love of comfort.",
           "Rat":"Intelligent, resourceful, and quick-witted, the Rat excels in finding opportunities and achieving success.",
           "Ox":"Strong, determined, and reliable, the Ox is known for its hardworking nature and steadfast loyalty.",
           "Tiger":"Bold, adventurous, and confident, the Tiger is a natural leader who thrives on challenges.",
           "Rabbit":"Gentle, compassionate, and creative, the Rabbit seeks peace and harmony in its surroundings."
}

Your task is to tweak your code to display the corresponding description of the zodiac sign for the given year.

unlock-access

Solution...

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

Chess Challenge: Checkmate in one move

For this challenge we will use a 8×8 2D array to represent the positions of all the black and white pieces on the chessboard.

We will then use Python Turtle to draw the chessboard using the information stored within the 2D array.

Here is the Python code for our 8×8 2D array:

board = [["bR","bN","bB","bQ","bK","bB","bN","bR"],
         ["bP","bP","bP","bP","bP","bP","bP","bP"],
         ["  ","  ","  ","  ","  ","  ","  ","  "],
         ["  ","  ","  ","  ","  ","  ","  ","  "],
         ["  ","  ","  ","  ","  ","  ","  ","  "],
         ["  ","  ","  ","  ","  ","  ","  ","  "],
         ["wP","wP","wP","wP","wP","wP","wP","wP"],
         ["wR","wN","wB","wQ","wK","wB","wN","wR"]]

In this challenge you will have to make some changes to the board array to move some pieces on the board and solve five different “Checkmate in one move puzzles”. To do you will have to edit the code provided.

Here is an example of how to move on of the white pawn by two places:

board[6][3] = "  " # Remove the white pawn on row 6, column 3
board[4][3] = "wP" # Reposition the white pawn to a new location: row 4, column 3

Checkmate in one move

The code provided below has 5 different puzzles where it is white’s turn to win the game in just one move. Edit the code to implement these moves.