At his birthday treasure hunt Manu Solved this code puzzle
Challenge Name: “Unlock the Code”
Background:
Your son has found an old computer terminal with a Python script running on it. The script is believed to be the key to opening a secret vault in the game. To unlock the vault, he must understand the script and determine the code it generates.
Python Script:
python
def mystery_function(x, y):
return x * y – x + y
def generate_code(seed):
result = []
for i in range(1, seed + 1):
result.append(mystery_function(i, seed – i))
return sum(result)
code = generate_code(4)
print(f”The secret code is: ???”)
Challenge:
By analyzing the Python script, determine the value of code and enter it to unlock the vault.
Hint (if he needs it):
The mystery function takes two numbers, multiplies them, and then subtracts the first number and adds the second number. To find the code, you need to understand how the generate_code function uses the mystery function to produce a sequence of numbers and then sums them up.
Solution Explanation:
The mystery_function simply multiplies two numbers and then subtracts the first number and adds the second number.
The generate_code function creates a list of numbers. It starts with i as 1 and the second argument of the mystery function as seed - 1. As i increases, the second argument decreases.
For seed = 4, the list of numbers generated would be:
mystery_function(1, 3)
mystery_function(2, 2)
mystery_function(3, 1)
mystery_function(4, 0)
The code is the sum of these numbers.
By working through the calculations, the correct answer to the challenge would be 10.
You can hide the line code = generate_code(4) if you want him to perform the calculations manually or you can leave it there if you want him to only understand the logic and then guess the correct value of the code.