More results...

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

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.

101Computing Dashboard

Are you looking for some inspiration for your next coding challenge? Do you need a selection of programmning projects for your coding club? Or maybe you would like to revise a computer science topic for your GCSE or A Level studies?

Our new dashboard contains a selection of coding challenges, interactive coding puzzles and GCSE and A Level computer science revision topics, all from this computing blog!

101 Computing DashboardOpen in New Window

The Egg Farmer’s Puzzle

An egg farmer is picking up eggs every morning to sell on the local market. Every day, they are picking around 100 to 150 eggs and put these eggs into egg cartons of 12 eggs.

So for instance, if on Monday our farmer picks up 128 eggs, they will use 10 cartons of 12 eggs. (10 x 12 = 120 eggs). With the remaining 8 eggs they will use a carton of 6:

This will mean that the farmer will be left with 2 spare eggs that they will eat for breakfast!

Our farmer would like to use a computer program to help them in the morning to pick up the right number of egg boxes to pack up all the eggs.

Your task is to write a Python program that will:

    Ask the farmer to enter how many eggs they have picked up this morning.
    Work out how many boxes of 12 eggs will be needed today.
    Work out if the farmer will also need a box of 6.
    Finally let the farmer know how many eggs they will have left to cook for breakfast.

Python Codde

Your task is to complete the Python code below:

Test Plan

Is your code complete? Let’s make sure it works as expected by completing the following test plan:

Test # Input Values Expected Output Pass/Fail?
#1 Number of Eggs: 128 You will need 10 cartons of 12.
You will need 1 carton of 6.
You will have 2 eggs for breakfast!
#2 Number of Eggs: 149 You will need 12 cartons of 12.
You will have 5 eggs for breakfast!
#3 Number of Eggs: 105 You will need 8 cartons of 12.
You will need 1 carton of 6.
You will have 3 eggs for breakfast!
unlock-access

Solution...

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