More results...

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

Charles Babbage’s Analytical Engine Emulator

In 19th-century London, Charles Babbage, an English mathematician and inventor, embarked on a groundbreaking quest to build the Analytical Engine, a mechanical precursor to the modern computer. Frustrated by errors in manual calculations, Babbage envisioned a machine capable of performing complex computations through programmable instructions. His collaboration with Ada Lovelace, who wrote the first computer program for the engine, revealed its full potential, laying the foundation for the digital age and establishing Lovelace as the world’s first computer programmer.

The Genesis of the Analytical Engine

Charles Babbage’s journey began with the Difference Engine, a mechanical calculator designed to compute polynomial functions. You can use our online difference engine emulator to find out more about this invention. Babbage’s ambition extended far beyond simple calculations: he envisioned a machine capable of performing any mathematical operations, guided by a set of instructions — a concept we now recognise as programming. This vision culminated in the design of the Analytical Engine.

The Collaboration with Ada Lovelace

Ada Lovelace, the daughter of the poet Lord Byron, is celebrated for her collaboration with Babbage on the Analytical Engine. Lovelace’s deep understanding of the engine’s potential led her to write a series of notes translating and expanding upon an Italian article about the engine. In these notes, she described an algorithm for the engine to compute Bernoulli numbers, which is widely regarded as the first computer program. Her visionary insights into the engine’s capabilities earned her the title of the world’s first computer programmer.

Main Components of the Analytical Engine

The Analytical Engine comprised several key components, each serving a distinct function:

The Mill: This was the computational heart of the engine, responsible for performing arithmetic operations. It was akin to the central processing unit (CPU) in modern computers, executing instructions and manipulating data.

The Store: This component served as the memory of the engine, holding numbers and intermediate results. It was analogous to today’s random-access memory (RAM), storing data that the Mill could retrieve and process. The approach used to store decimal numbers (as opposed to binary numbers in modern computers) using mechanical cog wheels was already a key concept of Charles Babbage’s difference engine.

The Card Reader: The engine was designed to accept input through punched cards, a concept borrowed from the Jacquard loom, a device used in the textile industry: The loom used punched cards to control the weaving of intricate patterns.

The Control Unit: This component directed the sequence of operations, determining which instructions the Mill should execute and when. It was the precursor to the control unit in modern computers, managing the flow of data and instructions.

The PrinterThe result of calculations performed by the Mill was envisioned to be either printed or punched onto cards.

The Analytical Engine Emulator

Despite its revolutionary design, the Analytical Engine was never fully constructed. This is mainy due to the technological limitations and high costs of precision engineering in the 19th century, as well as Babbage’s struggles to secure consistent funding and support for the project.

From the documentation produce by Charles Babbage and Ada Lovelace we can however understand and predict how the machine was intended to operate. The documentation describes the different sets of punched cards (instructions) that the machine had been designed to process. The work of John Walker published on his website (fourmilab), will provide you detailed information about the Analytical Engine and how it operates.

We have recreated here a functioning emulator the Analytical Engine of the to demonstrate how the machine was designed to operate. This emulator include pre-built programs that you can load and test online.
Charles Babbage’s Analytical Engine SimulatorOpen in new tab/window

The Inspiration Behind Punched Cards

Babbage’s idea of using punched cards to program the Analytical Engine was inspired by the Jacquard loom, invented by Joseph Marie Jacquard in 1804. The loom used punched cards to automate the weaving of complex patterns, revolutionising the textile industry. Babbage recognised the potential of this technology for programming his engine, allowing it to perform complex sequences of operations automatically.

The table below describes the different instructions/punched cards the analytical engine would have been able to process:

Opcode Instruction Example Description
N Number N1 5 Used to store a given number (e.g. 5) in the store at a specific location (e.g. 1)
L Load L2 Load a value from the store, at a specified location (e.g. 2) to the Mill Ingress axis, leaving the store column unchanged.
Z Load Z2 Load a value from the store, at a specified location/column (e.g. 2) to the Mill Ingress axis, resetting the store column to 0.
S Save S2 Store the value currently in the Mill Egress axis to a given location/column in the Store.
+ Add + Add the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this addition is stored in the Egress Axis.
Subtract Subtract the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this subtraction is stored in the Egress Axis.
x Multiply Multiply the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this multiplication is stored in the Egress Axis.
/ Divide / The value in the first Ingress Axis is divided by the value in the second Ingress Axis. The quotient is placed on the Primed Egress Axis and the remainder on the Egress Axis.
< Step up <6 Step up (left right) by n digits in the Ingress Axis. e.g. <3 to multiply the Ingress value by 1,000.
> Step down >6 Step down (shift right) by n digits in the Ingress Axis. e.g. >3 to divide the Ingress value by 1,000.
CB+ Back Always CB+7 To skip backward (and repeat) a given number of cards in the reader.
CB? Back only if run-up lever is set CB?7 To skip backward (and repeat) a given number of cards in the reader if run-up lever is set.
CF+ Forward Always CF+7 To skip forward a given number of cards in the reader.
CF? Forward only if run-up lever is set CF?7 To skip forward a given number of cards in the reader if run-up lever is set.
P Print P Print the value on the mill axis that the most recent operation most recently modified (e.g. the Mill Egress axis after an arithmetic operation, the Ingress axis after a L instruction, etc.).
B Bell B Ring the bell to get the attention of the engine attendant.
H Halt H Stop the engine. Stop the execution of the program.

Similarities and Differences with Modern Computers

The Analytical Engine shared several similarities with modern computers:

Programmability: Both can be programmed to perform a wide range of tasks, guided by a set of instructions.
Memory and Processing: The Store and Mill in the Analytical Engine are analogous to memory and CPU in modern computers.
Input/Output: Both use mechanisms for inputting data and outputting results, although the methods differ.

However, there are also significant differences:

Mechanical vs. Electronic: The Analytical Engine was purely mechanical, relying on gears and levers, while modern computers are electronic, using transistors and circuits.
Size and Speed: Modern computers are exponentially faster and more compact than the Analytical Engine, which was never fully constructed due to its complexity and the limitations of 19th-century technology.
Decimal vs. Binary: The Analytical Engine processed decimal numbers, reflecting the mathematical conventions of its time. In contrast, modern computers operate using binary numbers, which are more efficient for electronic computation.

Read More…

Check the following two blog posts:

Creating a Visual Hierarchy in HTML/CSS

In this post, we will explore the concept of visual hierarchy and how you can use your coding skills to recreate a specific visual layout. By the end of this challenge, you will have a better understanding of how to draw the reader’s attention to specific sections of a webpage using HTML and CSS. But first, let’s start with a short experiment. Check the picture below and check if it worked.

Did it work? In other words, did you read the text in the order mentioned on the picture?

Understanding the Concept of Visual Hierarchy

Visual hierarchy is a design principle that guides the viewer’s eye through different elements on a graphic or on a page, emphasising some over others. It is crucial in both print and digital media to ensure that the most important information stands out. For example, on a book cover, the title or the author’s name might be emphasised using larger fonts, bold colours, or strategic placement.

In web design, visual hierarchy helps users navigate and understand the content quickly. By using different sizes, colours, and placements, you can guide the user’s attention to the most critical parts of your webpage.

Coding Challenge: Recreate the Visual Hierarchy

Your task is to recreate the visual hierarchy similar to the one shown in the above image, using HTML and CSS. This layout uses text elements of varying sizes and positions to create a clear hierarchy.

To achieve this layout, you will need to use several CSS properties that control text formatting, positioning, and spacing. Here are some of the main properties you’ll use:

CSS Properties to Format Text:

  • font-family: Changes the font type used for the text. (e.g. Arial, Times New Roman, Verdana, etc.)
  • font-size: Controls the size of the text. Larger sizes draw more attention.
  • font-weight: Makes text bold or normal. Bold text stands out more.
  • font-style: Makes text italic or normal.
  • color: Sets the colour of the text. Contrasting colours can highlight important information.
  • text-align: Aligns text to the left, right, center, or justified.

Positioning and Alignment:

  • position: Allows you to position elements using values like static, relative, absolute, fixed, or sticky.
  • top, bottom, left, right: Used with position to specify the exact placement.
  • display: Controls the display behavior (e.g., block, inline, flex).

Spacing:
To understand the concepts of margin, padding and borders you may want to do some quick research on understanding the “CSS Box Model”.

  • margin: Adds space outside an element, pushing other elements away.
  • padding: Adds space inside an element, increasing the area between the content and the border.
  • border: Adds a border around an element, which can be used to separate or highlight sections.

HTML/CSS Code

Here is a basic example to get you started. You will need to apply more CSS properties to the different elements of the page to create your own visual hierarchy.

See the Pen
Creating a Visual Hierarchy
by 101 Computing (@101Computing)
on CodePen.


unlock-access

Solution...

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

Charles Babbage’s Difference Engine Emulator

In this blog post we will investigate the work of Charles Babbage with a particular focus on one of his most famous inventions: the Difference Engine. This invention constitutes a pioneering step in Computer Science. We will also explore the collaboration between Charles Babbage and Ada Lovelace who is considered to be the first computer programmer!

Who Was Charles Babbage?

Charles Babbage (1791-1871) was an English mathematician, philosopher, inventor, and mechanical engineer. He is widely recognised as one of the pioneers of computing, having designed the first automatic computing engines. Babbage’s contributions extended beyond computing; he also invented the cowcatcher for trains, improved the British postal system, and made significant advancements in cryptography and operations research. His work laid the foundation for modern computing and had a profound impact on the development of computer science.

What is the Difference Engine?

The Difference Engine is an automatic mechanical calculator designed to tabulate polynomial functions. It was conceived by Charles Babbage in the 1820s and was intended to produce error-free mathematical tables, particularly logarithm tables used in navigation. The engine operated on the method of finite differences, which allowed it to compute values of polynomial functions using a small set of coefficients.

The Difference Engine was a significant advancement over previous calculating machines. It used the decimal number system and was powered by a hand crank. The machine was designed to calculate a series of values and print the results automatically in a table. This automation was crucial because it reduced the likelihood of human error in the calculation and transcription of mathematical tables, which were essential for various scientific and engineering applications.

The primary use of the Difference Engine was to produce accurate mathematical tables. These tables were vital for navigation, engineering, and scientific research. Before the Difference Engine, tables were calculated by hand, a process that was time-consuming and prone to errors. Babbage’s machine aimed to make this process more efficient and reliable. The British government supported the project, hoping it would make the production of tables more economical and accurate.

Difference Engine Simulator

Use our online Difference Engine Emulator to find out more about Charles Babbage’s invention. In the example below, the engine is set up to tabulate the polynomial values of Euler’s polynomial: P(x)=x2+x+41

The particularity of this polynomial is that it generates only prime values for the first 40 integer values of x, starting with x=0: F(0) = 41, F(1) = 43, F(2) = 47, ⋯, F(39) = 1601. You can use the emulator to tabulate the first 40 values of Euler’s polynomial one value at a time using the following button:

Alternatively, you can use the “Settings” button to enter your own polynomial function.


The Difference Engine is considered one of the earliest examples of a computing device and a precursor to modern computers. Although Babbage’s original design was never fully realised during his lifetime due to technological and financial constraints, his concepts influenced the development of later computing machines. The principles behind the Difference Engine, such as the use of mechanical components to perform calculations and the automation of repetitive tasks, are fundamental to modern computing.

Babbage’s work also inspired future generations of inventors and scientists. His ideas about programmable machines and the use of punched cards for input, which he developed further in his Analytical Engine, were influential in the design of early electronic computers. The Difference Engine represents a crucial step in the evolution of computing, bridging the gap between manual calculation and automated computation.

Ada Lovelace’s Contribution to Charles Babbage’s Work

Ada Lovelace, born Augusta Ada Byron in 1815, was an English mathematician and writer. She is widely recognised for her work on Charles Babbage’s early mechanical general-purpose computer, the Analytical Engine. Her contributions to the field of computer science were ground-breaking and have earned her the title of the first computer programmer.

Ada Lovelace met Charles Babbage in 1833 when she was just 17 years old. Babbage, impressed by her intellectual capabilities, became her mentor and friend. Lovelace was fascinated by Babbage’s Difference Engine and later became deeply involved in his work on the Analytical Engine. Their collaboration was marked by a shared enthusiasm for scientific and mathematical inquiry, and their partnership played a crucial role in the early development of computing.

In 1842, Lovelace translated an article by Italian engineer Luigi Menabrea about the Analytical Engine from French to English. During this translation, she added extensive notes that were longer than the original article itself. These notes, published in 1843, included what is considered the first algorithm intended to be carried out by a machine, making Lovelace the first computer programmer. Her notes also explored the potential of the Analytical Engine beyond mere calculations, suggesting that it could be used for more complex tasks, including composing music and manipulating symbols.

Lovelace’s contributions laid the theoretical groundwork for computer programming. She understood that the Analytical Engine could follow a sequence of instructions — a program — to perform complex calculations. Her vision went beyond the capabilities of the machine as envisioned by Babbage, recognising that the engine could work with “other things besides number,” such as symbols and letters. This foresight was a fundamental shift from calculation to computation, a concept that is central to modern computing.

Ada Lovelace’s work has had a lasting impact on the field of computer science. Her insights into the potential of computing machines were far ahead of her time. Although the Analytical Engine was never fully built during her lifetime, her ideas influenced the development of early computers. In recognition of her contributions, a programming language developed by the U.S. Department of Defence in the 1970s was named “Ada” in her honour. Additionally, Ada Lovelace Day, celebrated on the second Tuesday of October, honours women’s contributions to science, technology, engineering, and mathematics (STEM).

Find Out More about the Difference Engine

About Charles Babbage Difference Engine №2 – Source: Science Museum Group
User Manual for the Difference Engine №2 – Source: Science Museum Group

Read More about the collaboration between Charles Babbage and Ada Lovelace

Internet History Timeline – Python Challenge

In this challenge, you will create two Python programs that quizzes users on key milestones from the history of the internet. Our program will let the player opt between two different types of quizzes:

  • Guess The Year Quiz: The program will randomly pick a key milestones from a provided Internet History Timeline (stored as a CSV file) and ask users to guess the year in which the selected milestone occurred.
  • Before or After Quiz: This second quiz will will randomly pick two key milestones from the Internet History Timeline and ask the user to guess which of these two key milestones occurred first .

By completing this challenge, you will improve your Python skills while learning about the fascinating history of the internet.

Internet History Timeline

There are many factors which have had a major impact in the development of the Internet since the late 1960s to the present day. Technological inventions in computer hardware, network concepts and protocols but also the launch of widely used websites which have been adopted by millions if not billions of Internet users worldwide.

Let’s revisit some of these key milestones presented on the following timeline:

Internet History TimelineOpen a new window

Guess The Year Quiz

We have started the code to create a “Guess The Year Quiz”. Our code randomly picks up a milestone from the internet-timeline.csv file provided in the tab below. It then display this milestone on the screen and ask the user to guess the year of this milestone.

Our code is however incomplete. To finalise this quiz you will need to:

    Check the annotated code provided below to see how the code randomly pick a question using the provided CSV file
    Use a loop to generate 10 different questions
    Add a scoring system to calculate and display a total score out of 10.

Before or After Quiz

Now that you understand how the code for the “Guess The Year” quiz works, re-use a similar approach to create the second quiz called “Before or After?”. Your program will need to:

    Randomly pick two milestones from the Internet History Timeline (using the provided CSV file)
    Display both milestones on the screen
    Ask the user to guess which of the two milestones occurred first
    Check the user’s guess and provide feedback on their guess
    Use a loop to generate 10 different questions
    Add a scoring system to calculate and display a total score out of 10.
unlock-access

Solution...

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

Lossless Compression Algorithms using Python

In today’s data-driven world, efficient storage and transmission of information are more critical than ever. Lossless compression techniques play a pivotal role in achieving this efficiency by reducing data size without compromising its integrity. Unlike lossy compression, which sacrifices some data to achieve higher compression rates, lossless methods ensure that the original data can be perfectly reconstructed from its compressed form. This makes lossless compression ideal for applications where data accuracy is paramount, such as text files, computer programs, executables, and databases.

In this blog post, we will focus on two fundamental lossless compression techniques: dictionary encoding and run-length encoding. By implementing these methods in Python, we will demonstrate their effectiveness in compressing a list of colours representing the different Lego bricks needed to build a colourful Lego tower.

Dictionary Encoding

Dictionary encoding, also known as substitution encoding, replaces recurring elements with shorter codes or symbols. This technique is effective when the data contains many repetitions. For our LEGO tower, we can use dictionary encoding to replace frequently occurring colours with shorter identifiers as follows:

Run-Length Encoding

Run-length encoding (RLE) is a simple form of data compression where consecutive elements (runs) are stored as a single data value and count. This technique is particularly effective for data with many consecutive repetitions. In our Lego tower, RLE can compress sequences of the same colour into a more compact form:

Combing Dictionary Encoding and Run-Length Encoding

By combining both lossless compression methods it may be possible to reach a higher compression rate, still without losing any data (lossless compression)!

Lossless Compression Algorithms, using Python!

Let’s use our Python skills to implement the two lossless compression techniques described above. To fully understand the code provided below, you will need a good understanding of how lists, dictionaries (a.k.a. hash tables) and tuples work in Python. You may first notice the use of square brackets [] in Python for storing data in a list, the use of curly brackets {} for storing pairs of key:value in a dictionary and the use of standard brackets () to store data in a tuple.

Use the tabs below to investigate how we have implemented our compression algorithms to compress our list of Lego brick colours.

Dictionary EncodingRun-Length EncodingDictionary Encoding + Run-Length Encoding
Our dictionary_compress() function will take one parameter, the data (list of values) to be compressed and return both a compressed list of encoded values as well as a dictionary that would be needed to decompress the data.

# Dictionary Encoding
def dictionary_encoding(data):
   compressedData = []
   dictionary = {}
   reversedDictionary = {}

   for value in data:
      if value not in reversedDictionary:
         key = value[0]     # e.g. "Y" for "Yellow"
         dictionary[key] = value     # "Y":"Yellow"
         reversedDictionary[value] = key  # "Yellow":"Y"
         compressedData.append(key)    # "Y"
      else:
         key = reversedDictionary[value]
         compressedData.append(key)
   return compressedData, dictionary

data = ["Yellow","Yellow","Yellow","Red","Red","Blue","Blue","Blue","Green","Red"]
print(">>> Original Data (Before compression)")
print(data)      
print("")
compressedData, dictionary = dictionary_encoding(data)
print(compressedData)
print(dictionary)
Our run_length_compress() function will take one parameter, the data (list of values) to be compressed and return a list of tuples to indicate the number of consecutive occurrences of each value.

# Run-Length Encoding
def run_length_encoding(data):
   compressedData = []
   currentKey = data[0]
   counter = 1
   for i in range(1,len(data)):
      if data[i]==currentKey:
         counter+=1
      else:
         compressedData.append((currentKey,counter))
         counter=1
         currentKey = data[i]
   compressedData.append((currentKey,counter))  
   return compressedData

data = ["Yellow","Yellow","Yellow","Red","Red","Blue","Blue","Blue","Green","Red"]
print(">>> Original Data (Before compression)")
print(data)      
print("")
compressedData = run_length_encoding(data)
print(compressedData)
We can now create a lossless_compress() function that will reuse both our lossless compression functions: dictionary_compress() and run_length_compress()

# Lossless Compression Algorithms using Python - www.101computing.net/lossless-compression-algorithms-using-python

# Dictionary Encoding
def dictionary_encoding(data):
   compressedData = []
   dictionary = {}
   reversedDictionary = {}

   for value in data:
      if value not in reversedDictionary:
         key = value[0]     # e.g. "Y" for "Yellow"
         dictionary[key] = value     # "Y":"Yellow"
         reversedDictionary[value] = key  # "Yellow":"Y"
         compressedData.append(key)    # "Y"
      else:
         key = reversedDictionary[value]
         compressedData.append(key)
   return compressedData, dictionary

# Run-Length Encoding
def run_length_encoding(data):
   compressedData = []
   currentKey = data[0]
   counter = 1
   for i in range(1,len(data)):
      if data[i]==currentKey:
         counter+=1
      else:
         compressedData.append((currentKey,counter))
         counter=1
         currentKey = data[i]
   compressedData.append((currentKey,counter))  
   return compressedData

# Combining Both Lossless Compression Techniques
def lossless_compression(data):
   print(" >>> Step 1: Dictionary Encoding")
   compressedData, dictionary = dictionary_encoding(data)
   print(" > Compressed Data:")
   print(compressedData)  

   print(" > Dictionary:")
   print(dictionary)
   print("")
   print(" >>> Step 2: Run-Length Encoding")
   fullyCompressedData = run_length_encoding(compressedData)
   print(" > Fully Compressed Data:")
   print(fullyCompressedData)        
   
  
data = ["Yellow","Yellow","Yellow","Red","Red","Blue","Blue","Blue","Green","Red"]
print(">>> Original Data (Before compression)")
print(data)      
print("")
lossless_compression(data)

Try it online…

You can now test these functions using the code provided below…

Python Challenge

Your Python challenge is to write an algorithm to decompress data using a list of compressed data and a given dictionary, your python code will need to reconstruct the original data:

unlock-access

Solution...

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

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