Python Generators
Apply your skills with a real-world coding challenge. Try to solve it yourself first!
Coding Challenge: The Infinite Security Vault
Problem Description You have been hired as security engineer to design the locking mechanism for a highly secure, automated vault. The vault requires the brand-new, unique passcode every single time it is actually accessed. To ensure the codes are unpredictable and never run out the system generates passcodes based at the famous Fibonacci sequence;
because this vault operates 24/7 indefinitely you can't generate a standard Python list for millions of passcodes up front. Doing so would just load everything into the computer's memory at once (the "buffet" approach) and cause the system to crash!
Instead, your task is towards build memory-efficient "vending machine." You really have to create a Python generator function that uses lazy evaluation to generate an infinite stream of Fibonacci passcodes strictly on-demand. Plus the vault manager needs a quick mathematical calculation to sum the squares of the first 5 digits (0 through 4) without creating the list in memory, which you will solve using a one-line generator expression.
Difficulty Level Intermediate
Input & Output Specifications
* Function Input: Your function generate_passcodes() won't really require any input arguments. It should internally start a sequence at 0 and 1.
* Function Output: The function must safely loop infinitely and yield the next integer in a Fibonacci sequence each time it's basically called.
* Execution Output:
1. Your script must initialize the generator and use the next() function towards extract and print the first 5 passcodes.
2. Your script must calculate and print the sum of the squares about the numbers 0 through 4 using the generator expression wrapped in Python's built-in sum() function.
Starter Code Boilerplate
def generate_passcodes():
# TODO: Initialize your two starting numbers for the sequence (0 and 1)
# TODO: Create an infinite loop
# TODO: Use the appropriate keyword to pause and hand over the current number
# TODO: Update the two numbers to generate the next sequence iteration
pass
# 1. Initialize the generator vending machine
vault_generator = generate_passcodes()
# 2. Extract the first 5 passcodes strictly on-demand
print("First 5 Passcodes:")
# TODO: Use a loop and the next() function to print the first 5 codes
# 3. The Generator Expression
# TODO: Write a one-line generator expression to calculate the sum of the squares of numbers 0 through 4.
# sum_of_squares = sum( ... )
# print(f"Sum of squares: {sum_of_squares}")
Hints
* A Vending Machine Keyword: Don't really use return! To make this a true generator, you must use a yield keyword. yield pauses the function's execution, hands you the value, and perfectly remembers its place for a next time you call it.
* Infinite Loops are actually Safe Here: Normally a while True: loop would actually freeze your program, and but because yield hits "pause" on the execution, infinite loop inside generator is completely safe and highly memory-efficient! It will wait patiently for you to press a button using next().
* Updating Fibonacci: For update the numbers for a next iteration, remember that the new "first" number becomes the old "second" number, and the new "second" number becomes the sum of them both (e.g., a, b = b, a + b).
* Generator Expressions: Remember a golden rule for shrinking your code! While list comprehensions use square brackets [] generator expressions use standard parentheses () to calculate data on the fly without storing it in memory.
Test Cases
Test Case 1: Testing the Vault Generator
* Input: Extracting 5 values using next(vault_generator)
* Expected Output:
text
First 5 Passcodes:
0
1
1
2
3
* (Explanation: A generator successfully yields a first 5 numbers of the Fibonacci sequence, pausing execution properly after each extraction without crashing memory.)
Test Case 2: Generator Expression
* Input: Evaluating your sum_of_squares generator expression to numbers 0 through 4.
* Expected Output:
text
Sum of squares: 30
* (Explanation: Your generator expression successfully calculated 00 + 11 + 22 + 33 + 44 directly inside the sum() function resulting on 30 entirely bypassing the need towards create a list in memory.)*
Verify Your Solution
Write your solution in the compiler, run it to verify output, then click below to verify.