Posted on Leave a comment

How to Filter a List of Dictionaries in Python?

In this article, you’ll learn the ins and outs of the sorting function in Python. In particular, you’re going to learn how to filter a list of dictionaries. So let’s get started!

Short answer: The list comprehension statement [x for x in lst if condition(x)] creates a new list of dictionaries that meet the condition. All dictionaries in lst that don’t meet the condition are filtered out. You can define your own condition on list element x.

Here’s a quick and minimal example:

l = [{'key':10}, {'key':4}, {'key':8}] def condition(dic): ''' Define your own condition here''' return dic['key'] > 7 filtered = [d for d in l if condition(d)] print(filtered)
# [{'key': 10}, {'key': 8}]

Try it yourself in the interactive Python shell (in your browser):

You’ll now get the step-by-step solution of this solution. I tried to keep it as simple as possible. So keep reading!

Filter a List of Dictionaries By Value

Problem: Given a list of dictionaries. Each dictionary consists of one or more (key, value) pairs. You want to filter them by value of a particular dictionary key (attribute). How do you do this?

Minimal Example: Consider the following example where you’ve three user dictionaries with username, age, and play_time keys. You want to get a list of all users that meet a certain condition such as play_time>100. Here’s what you try to accomplish:

users = [{'username': 'alice', 'age': 23, 'play_time': 101}, {'username': 'bob', 'age': 31, 'play_time': 88}, {'username': 'ann', 'age': 25, 'play_time': 121},] superplayers = # Filtering Magic Here print(superplayers)

The output should look like this where the play_time attribute determines whether a dictionary passes the filter or not, i.e., play_time>100:

[{'username': 'alice', 'age': 23, 'play_time': 101}, {'username': 'ann', 'age': 25, 'play_time': 121}]

Solution: Use list comprehension [x for x in lst if condition(x)] to create a new list of dictionaries that meet the condition. All dictionaries in lst that don’t meet the condition are filtered out. You can define your own condition on list element x.

Here’s the code that shows you how to filter out all user dictionaries that don’t meet the condition of having played at least 100 hours.

users = [{'username': 'alice', 'age': 23, 'play_time': 101}, {'username': 'bob', 'age': 31, 'play_time': 88}, {'username': 'ann', 'age': 25, 'play_time': 121},] superplayers = [user for user in users if user['play_time']>100] print(superplayers)

The output is the filtered list of dictionaries that meet the condition:

[{'username': 'alice', 'age': 23, 'play_time': 101}, {'username': 'ann', 'age': 25, 'play_time': 121}]

Try It Yourself:

Related articles on the Finxter blog:

Filter a List of Dictionaries By Key

Problem: Given a list of dictionaries. Each dictionary consists of one or more (key, value) pairs. You want to filter them by key (attribute). All dictionaries that don’t have this key (attribute) should be filtered out. How do you do this?

Minimal Example: Consider the following example again where you’ve three user dictionaries with username, age, and play_time keys. You want to get a list of all users for which the key play_time exists. Here’s what you try to accomplish:

users = [{'username': 'alice', 'age': 23, 'play_time': 101}, {'username': 'bob', 'age': 31, 'play_time': 88}, {'username': 'ann', 'age': 25},] superplayers = # Filtering Magic Here print(superplayers)

The output should look like this where the play_time attribute determines whether a dictionary passes the filter or not (as long as it exists, it shall pass the filter).

[{'username': 'alice', 'age': 23, 'play_time': 101}, {'username': 'bob', 'age': 31, 'play_time': 88}]

Solution: Use list comprehension [x for x in lst if condition(x)] to create a new list of dictionaries that meet the condition. All dictionaries in lst that don’t meet the condition are filtered out. You can define your own condition on list element x.

Here’s the code that shows you how to filter out all user dictionaries that don’t meet the condition of having a key play_time.

users = [{'username': 'alice', 'age': 23, 'play_time': 101}, {'username': 'bob', 'age': 31, 'play_time': 88}, {'username': 'ann', 'age': 25},] superplayers = [user for user in users if 'play_time' in user] print(superplayers)

The output is the filtered list of dictionaries that meet the condition:

[{'username': 'alice', 'age': 23, 'play_time': 101}, {'username': 'bob', 'age': 31, 'play_time': 88}]

Try It Yourself:

Related articles on the Finxter blog:

Related Question: How to Sort a List of Dictionaries By Key Value

Original article

Problem: Given a list of dictionaries. Each dictionary consists of multiple (key, value) pairs. You want to sort them by value of a particular dictionary key (attribute). How do you sort this dictionary?

Minimal Example: Consider the following example where you want to sort a list of salary dictionaries by value of the key 'Alice'.

salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] sorted_salaries = # ... Sorting Magic Here ... print(sorted_salaries)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{'Alice': 12000, 'Bob': 66000},
{'Alice': 100000, 'Bob': 24000},
{'Alice': 121000, 'Bob': 48000}]

Solution: You have two main ways to do this—both are based on defining the key function of Python’s sorting methods. The key function maps each list element (in our case a dictionary) to a single value that can be used as the basis of comparison.

  • Use a lambda function as key function to sort the list of dictionaries.
  • Use the itemgetter function as key function to sort the list of dictionaries.

Here’s the code of the first option using a lambda function that returns the value of the key 'Alice' from each dictionary:

# Create the dictionary of Bob's and Alice's salary data
salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] # Use the sorted() function with key argument to create a new dic.
# Each dictionary list element is "reduced" to the value stored for key 'Alice'
sorted_salaries = sorted(salaries, key=lambda d: d['Alice']) # Print everything to the shell
print(sorted_salaries)

The output is the sorted dictionary. Note that the first dictionary has the smallest salary of Alice and the third dictionary has the largest salary of Alice.

[{'Alice': 12000, 'Bob': 66000}, {'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}]

Try It Yourself:

Related articles:

Where to Go From Here

In this article, you’ve learned how to filter a list of dictionaries easily with a simple list comprehension statement. That’s far more efficient than using the filter() method proposed in many other blog tutorials. Guido, the creator of Python, hated the filter() function!

I’ve realized that professional coders tend to use dictionaries more often than beginners due to their superior understanding of the benefits of dictionaries. If you want to learn about those, check out my in-depth tutorial of Python dictionaries.

If you want to stop learning and start earning with Python, check out my free webinar “How to Become a Python Freelance Developer?”. It’s a great way of starting your thriving coding business online.

“[Webinar] How to Become a Python Freelance Developer?”

Posted on Leave a comment

Python List Methods Cheat Sheet [Instant PDF Download]

Here’s your free PDF cheat sheet showing you all Python list methods on one simple page. Click the image to download the high-resolution PDF file, print it, and post it to your office wall:

I’ll lead you through all Python list methods in this short video tutorial:

If you want to study the methods yourself, have a look at the following table from my blog article:

Method Description
lst.append(x) Appends element x to the list lst.
lst.clear() Removes all elements from the list lst–which becomes empty.
lst.copy() Returns a copy of the list lst. Copies only the list, not the elements in the list (shallow copy).
lst.count(x) Counts the number of occurrences of element x in the list lst.
lst.extend(iter) Adds all elements of an iterable iter(e.g. another list) to the list lst.
lst.index(x) Returns the position (index) of the first occurrence of value x in the list lst.
lst.insert(i, x) Inserts element x at position (index) i in the list lst.
lst.pop() Removes and returns the final element of the list lst.
lst.remove(x) Removes and returns the first occurrence of element x in the list lst.
lst.reverse() Reverses the order of elements in the list lst.
lst.sort() Sorts the elements in the list lst in ascending order.

Go ahead and try the Python list methods yourself:

Puzzle: Can you figure out all outputs of this interactive Python script?

If you’ve studied the table carefully, you’ll know the most important list methods in Python. Let’s have a look at some examples of above methods:

>>> l = []
>>> l.append(2)
>>> l
[2]
>>> l.clear()
>>> l
[]
>>> l.append(2)
>>> l
[2]
>>> l.copy()
[2]
>>> l.count(2)
1
>>> l.extend([2,3,4])
>>> l
[2, 2, 3, 4]
>>> l.index(3)
2
>>> l.insert(2, 99)
>>> l
[2, 2, 99, 3, 4]
>>> l.pop()
4
>>> l.remove(2)
>>> l
[2, 99, 3]
>>> l.reverse()
>>> l
[3, 99, 2]
>>> l.sort()
>>> l
[2, 3, 99]

Where to Go From Here?

Want more cheat sheets? Excellent. I believe learning with cheat sheets is one of the most efficient learning techniques. Join my free Python email list where I’ll send you more than 10 new Python cheat sheets and regular Python courses for continuous improvement. It’s free!

Posted on Leave a comment

How to Split a List Into Evenly-Sized Chunks?

In this article, I’ll show you how to divide a list into equally-sized chunks in Python. Step-by-step, you’ll arrive at the following great code that accomplishes exactly that:

You can play around with the code yourself but if you need some explanations, read on because I’ll explain it to you in much detail:

Chunking Your List

Let’s make this question more palpable by transforming it into a practical problem:

Problem: Imagine that you have a temperature sensor that sends data every 6 minutes, which makes 10 data points per hour. All these data points are stored in one list for each day.

Now, we want to have a list of hourly average temperatures for each day—this is why we need to split the list of data for one day into evenly sized chunks.

Solution: To achieve this, we use a for-loop and Python’s built-in function range() which we have to examine in depth.

The range() function can be used either with one, two or three arguments.

  • If you use it with one single argument, e.g., range(10), we get a range object containing the numbers 0 to 9. So, if you call range with one argument, this argument will be interpreted as the max or stop value of the range, but it is excluded from the range.
  • You can also call the range() function with two arguments, e.g., range(5, 10). This call with two arguments returns a range object containing the numbers 5 to 9. So, now we have a lower and an upper bound for the range. Contrary to the stop value, the start value is included in the range.
  • In a call of the function range() with three parameters, the first parameter is the start value, the second one is the stop value and the third value is the step size. For example, range(5, 15, 2) returns a range object containing the following values: 5, 7, 9, 11, 13. As you can see, the range starts with the start and then it adds the step value as long as the values are less than the stop value.

In our problem, our chunks have a length of 10, the start value is 0 and the max value is the end of the list of data.

Putting all together: Calling range(0, len(data), 10) will give us exactly what we need to iterate over the chunks. Let’s put some numbers there to visualize it.

For one single day, we have a data length of 24 * 10 = 240, so the call of the range function would be this: range(0, 240, 10) and the resulting range would be 0, 10, 20, 30, …, 230. Pause a moment and consider these values: they represent the indices of the first element of each chunk.

So what do we have now? The start indices of each chunk and also the length – and that’s all we need to slice the input data into the chunks we need.

The slicing operator takes two or three arguments separated by the colon : symbol. They have the same meaning as in the range function.

If you want to know more about slicing read our detailed article here.

A first draft of our code could be this:

data = [15.7, 16.2, 16.5, 15.9, ..., 27.3, 26.4, 26.1, 27.2]
chunk_length = 10 for i in range(0, len(data), chunk_length): print(data[i:i+chunk_length])

Play with this code in our interactive Python shell:

However, we can still improve this code and make it reusable by creating a generator out of it.

Chunking With Generator Expressions

A generator is a function but instead of a return statement it uses the keyword yield.

The keyword yield interrupts the function and returns a value. The next time the function gets called, the next value is returned and the function’s execution stops again. This behavior can be used in a for-loop, where we want to get a value from the generator, work with this value inside the loop and then repeat it with the next value. Now, let’s take a look at the improved version of our code:

data = [15.7, 16.2, 16.5, 15.9, ..., 27.3, 26.4, 26.1, 27.2]
chunk_length = 10 def make_chunks(data, length): for i in range(0, len(data), length): yield data[i:i + length] for chunk in make_chunks(data, chunk_length): print(chunk)

That looks already pretty pythonic and we can reuse the function make_chunks() for all the other data we need to process.

Let’s finish the code so that we get a list of hourly average temperatures as result.

import random def make_chunks(data, length): for i in range(0, len(data), length): yield data[i:i + length] def process(chunk): return round(sum(chunk)/len(chunk), 2) n = 10
# generate random temperature values
day_temperatures = [random.random() * 20 for x in range(24 * n)]
avg_per_hour = [] for chunk in make_chunks(day_temperatures, n): r = process(batch) avg_per_hour.append(r) print(avg_per_hour)

And that’s it, this cool pythonic code solves our problem. We can make the code even a bit shorter but I consider this code less readable because you need to know really advanced Python concepts.

import random make_chunks = lambda data, n: (data[i:i + n] for i in range(0, len(data), n))
process = lambda data: round(sum(data)/len(data), 2) n = 10
# generate random temperature values
day_temperatures = [random.random() * 20 for x in range(24 * n)]
avg_per_hour = [] for chunk in make_chunks(day_temperatures, n): r = process(batch) avg_per_hour.append(r) print(avg_per_hour)

So, what did we do? We reduced the helper functions to lambda expressions and for the generator function we use a special shorthand – the parenthesis.

Summary

To sum up the solution: We used the range function with three arguments, the start value, the stop value and the step value. By setting the step value to our desired chunk length, the start value to 0 and the stop value to the total data length, we get a range object containing all the start indices of our chunks. With the help of slicing we can access exactly the chunk we need in each iteration step.

Where to Go From Here?

Want to start earning a full-time income with Python—while working only part-time hours? Then join our free Python Freelancer Webinar.

It shows you exactly how you can grow your business and Python skills to a point where you can work comfortable for 3-4 hours from home and enjoy the rest of the day (=20 hours) spending time with the persons you love doing things you enjoy to do.

Become a Python freelancer now!

Posted on Leave a comment

How to Calculate the Column Standard Deviation of a DataFrame in Python Pandas?

Want to calculate the standard deviation of a column in your Pandas DataFrame?

In case you’ve attended your last statistics course a few years ago, let’s quickly recap the definition of variance: it’s the average squared deviation of the list elements from the average value.

You can do this by using the pd.std() function that calculates the standard deviation along all columns. You can then get the column you’re interested in after the computation.

import pandas as pd # Create your Pandas DataFrame
d = {'username': ['Alice', 'Bob', 'Carl'], 'age': [18, 22, 43], 'income': [100000, 98000, 111000]}
df = pd.DataFrame(d) print(df)

Your DataFrame looks like this:

username age income
0 Alice 18 100000
1 Bob 22 98000
2 Carl 43 111000

Here’s how you can calculate the standard deviation of all columns:

print(df.std())

The output is the standard deviation of all columns:

age 13.428825
income 7000.000000
dtype: float64

To get the variance of an individual column, access it using simple indexing:

print(df.std()['age'])
# 180.33333333333334

Together, the code looks as follows. Use the interactive shell to play with it!

Standard Deviation in NumPy Library

Python’s package for data science computation NumPy also has great statistics functionality. You can calculate all basic statistics functions such as average, median, variance, and standard deviation on NumPy arrays. Simply import the NumPy library and use the np.var(a) method to calculate the average value of NumPy array a.

Here’s the code:

import numpy as np a = np.array([1, 2, 3])
print(np.std(a))
# 0.816496580927726

Where to Go From Here?

Before you can become a data science master, you first need to master Python. Join my free Python email course and receive your daily Python lesson directly in your INBOX. It’s fun!

Join The World’s #1 Python Email Academy [+FREE Cheat Sheets as PDF]

Posted on Leave a comment

How to Use Generator Expressions in Python Dictionaries

Imagine the following scenario:

You work in law enforcement for the US Department of Labor, finding companies that pay below minimum wage so you can initiate further investigations. Like hungry dogs on the back of a meat truck, your Fair Labor Standards Act (FLSA) officers are already waiting for the list of companies that violated the minimum wage law. Can you give it to them?

Here’s the code from my new book “Python One-Liners“:

companies = {'CoolCompany' : {'Alice' : 33, 'Bob' : 28, 'Frank' : 29}, 'CheapCompany' : {'Ann' : 4, 'Lee' : 9, 'Chrisi' : 7}, 'SosoCompany' : {'Esther' : 38, 'Cole' : 8, 'Paris' : 18}} illegal = [x for x in companies if any(y<9 for y in companies[x].values())] print(illegal)

Try it yourself in our interactive Python shell:

Posted on Leave a comment

Python List Average

Don’t Be Mean, Be Median.

This article shows you how to calculate the average of a given list of numerical inputs in Python.

In case you’ve attended your last statistics course a few years ago, let’s quickly recap the definition of the average: sum over all values and divide them by the number of values.

So, how to calculate the average of a given list in Python?

Python 3.x doesn’t have a built-in method to calculate the average. Instead, simply divide the sum of list values through the number of list elements using the two built-in functions sum() and len(). You calculate the average of a given list in Python as sum(list)/len(list). The return value is of type float.

Here’s a short example that calculates the average income of income data $80000, $90000, and $100000:

income = [80000, 90000, 100000]
average = sum(income) / len(income)
print(average)
# 90000.0

You can see that the return value is of type float, even though the list data is of type integer. The reason is that the default division operator in Python performs floating point arithmetic, even if you divide two integers.

Puzzle: Try to modify the elements in the list income so that the average is 80000.0 instead of 90000.0 in our interactive shell:

<iframe height="700px" width="100%" src="https://repl.it/@finxter/averagepython?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>

If you cannot see the interactive shell, here’s the non-interactive version:

# Define the list data
income = [80000, 90000, 100000] # Calculate the average as the sum divided
# by the length of the list (float division)
average = sum(income) / len(income) # Print the result to the shell
print(average) # Puzzle: modify the income list so that
# the result is 80000.0

This is the absolute minimum you need to know about calculating basic statistics such as the average in Python. But there’s far more to it and studying the other ways and alternatives will actually make you a better coder. So, let’s dive into some related questions and topics you may want to learn!

Python List Average Median

What’s the median of a Python list? Formally, the median is “the value separating the higher half from the lower half of a data sample” (wiki).

How to calculate the median of a Python list?

  • Sort the list of elements using the sorted() built-in function in Python.
  • Calculate the index of the middle element (see graphic) by dividing the length of the list by 2 using integer division.
  • Return the middle element.

Together, you can simply get the median by executing the expression median = sorted(income)[len(income)//2].

Here’s the concrete code example:

income = [80000, 90000, 100000, 88000] average = sum(income) / len(income)
median = sorted(income)[len(income)//2] print(average)
# 89500.0 print(median)
# 90000.0

Related tutorials:

Python List Average Mean

The mean value is exactly the same as the average value: sum up all values in your sequence and divide by the length of the sequence. You can use either the calculation sum(list) / len(list) or you can import the statistics module and call mean(list).

Here are both examples:

lst = [1, 4, 2, 3] # method 1
average = sum(lst) / len(lst)
print(average)
# 2.5 # method 2
import statistics
print(statistics.mean(lst))
# 2.5

Both methods are equivalent. The statistics module has some more interesting variations of the mean() method (source):

mean() Arithmetic mean (“average”) of data.
median() Median (middle value) of data.
median_low() Low median of data.
median_high() High median of data.
median_grouped() Median, or 50th percentile, of grouped data.
mode() Mode (most common value) of discrete data.

These are especially interesting if you have two median values and you want to decide which one to take.

Python List Average Standard Deviation

Standard deviation is defined as the deviation of the data values from the average (wiki). It’s used to measure the dispersion of a data set. You can calculate the standard deviation of the values in the list by using the statistics module:

import statistics as s lst = [1, 0, 4, 3]
print(s.stdev(lst))
# 1.8257418583505538

Python List Average Min Max

In contrast to the average, there are Python built-in functions that calculate the minimum and maximum of a given list. The min(list) method calculates the minimum value and the max(list) method calculates the maximum value in a list.

Here’s an example of the minimum, maximum and average computations on a Python list:

import statistics as s lst = [1, 1, 2, 0]
average = sum(lst) / len(lst)
minimum = min(lst)
maximum = max(lst) print(average)
# 1.0 print(minimum)
# 0 print(maximum)
# 2

Python List Average Sum

How to calculate the average using the sum() built-in Python method? Simple, divide the result of the sum(list) function call by the number of elements in the list. This normalizes the result and calculates the average of all elements in a list.

Again, the following example shows how to do this:

import statistics as s lst = [1, 1, 2, 0]
average = sum(lst) / len(lst) print(average)
# 1.0

Python List Average NumPy

Python’s package for data science computation NumPy also has great statistics functionality. You can calculate all basic statistics functions such as average, median, variance, and standard deviation on NumPy arrays. Simply import the NumPy library and use the np.average(a) method to calculate the average value of NumPy array a.

Here’s the code:

import numpy as np a = np.array([1, 2, 3])
print(np.average(a))
# 2.0

Python Average List of (NumPy) Arrays

NumPy’s average function computes the average of all numerical values in a NumPy array. When used without parameters, it simply calculates the numerical average of all values in the array, no matter the array’s dimensionality. For example, the expression np.average([[1,2],[2,3]]) results in the average value (1+2+2+3)/4 = 2.0.

However, what if you want to calculate the weighted average of a NumPy array? In other words, you want to overweight some array values and underweight others.

You can easily accomplish this with NumPy’s average function by passing the weights argument to the NumPy average function.

import numpy as np a = [-1, 1, 2, 2] print(np.average(a))
# 1.0 print(np.average(a, weights = [1, 1, 1, 5]))
# 1.5

In the first example, we simply averaged over all array values: (-1+1+2+2)/4 = 1.0. However, in the second example, we overweight the last array element 2—it now carries five times the weight of the other elements resulting in the following computation: (-1+1+2+(2+2+2+2+2))/8 = 1.5.

Let’s explore the different parameters we can pass to np.average(...).

  • The NumPy array which can be multi-dimensional.
  • (Optional) The axis along which you want to average. If you don’t specify the argument, the averaging is done over the whole array.
  • (Optional) The weights of each column of the specified axis. If you don’t specify the argument, the weights are assumed to be homogeneous.
  • (Optional) The return value of the function. Only if you set this to True, you will get a tuple (average, weights_sum) as a result. This may help you to normalize the output. In most cases, you can skip this argument.

Here is an example how to average along the columns of a 2D NumPy array with specified weights for both rows.

import numpy as np # daily stock prices
# [morning, midday, evening]
solar_x = np.array(
[[2, 3, 4], # today
[2, 2, 5]]) # yesterday # midday - weighted average
print(np.average(solar_x, axis=0, weights=[3/4, 1/4])[1])

What is the output of this puzzle?
*Beginner Level* (solution below)

You can also solve this puzzle in our puzzle-based learning app (100% FREE): Test your skills now!

Related article:

Python Average List of Dictionaries

Problem: Given is a list of dictionaries. Your goal is to calculate the average of the values associated to a specific key from all dictionaries.

Example: Consider the following example where you want to get the average value of a list of database entries (e.g., each stored as a dictionary) stored under the key 'age'.

db = [{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Bob', 'joined': 2018, 'age': 19}, {'username': 'Alice', 'joined': 2020, 'age': 31}] average = # ... Averaging Magic Here ... print(average)

The output should look like this where the average is determined using the ages (23+19+31)/3 = 24.333.

Solution: Solution: You use the feature of generator expression in Python to dynamically create a list of age values. Then, you sum them up and divide them by the number of age values. The result is the average of all age values in the dictionary.

db = [{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Bob', 'joined': 2018, 'age': 19}, {'username': 'Alice', 'joined': 2020, 'age': 31}] average = sum(d['age'] for d in db) / len(db) print(average)
# 24.333333333333332

Let’s move on to the next question: how to calculate the average of a list of floats?

Python Average List of Floats

Averaging a list of floats is as simple as averaging a list of integers. Just sum them up and divide them by the number of float values. Here’s the code:

lst = [1.0, 2.5, 3.0, 1.5]
average = sum(lst) / len(lst)
print(average)
# 2.0

Python Average List of Tuples

Problem: How to average all values if the values are stored in a list of tuples?

Example: You have the list of tuples [(1, 2), (2, 2), (1, 1)] and you want the average value (1+2+2+2+1+1)/6 = 1.5.

Solution: There are three solution ideas:

  • Unpack the tuple values into a list and calculate the average of this list.
  • Use only list comprehension with nested for loop.
  • Use a simple nested for loop.

Next, I’ll give all three examples in a single code snippet:

lst = [(1, 2), (2, 2), (1, 1)] # 1. Unpacking
lst_2 = [*lst[0], *lst[1], *lst[2]]
print(sum(lst_2) / len(lst_2))
# 1.5 # 2. List comprehension
lst_3 = [x for t in lst for x in t]
print(sum(lst_3) / len(lst_3))
# 1.5 # 3. Nested for loop
lst_4 = []
for t in lst: for x in t: lst_4.append(x)
print(sum(lst_4) / len(lst_4))
# 1.5

Unpacking: The asterisk operator in front of an iterable “unpacks” all values in the iterable into the outer context. You can use it only in a container data structure that’s able to catch the unpacked values.

List comprehension is a compact way of creating lists. The simple formula is [ expression + context ].

  • Expression: What to do with each list element?
  • Context: What list elements to select? It consists of an arbitrary number of for and if statements.

The example [x for x in range(3)] creates the list [0, 1, 2].

Python Average Nested List

Problem: How to calculate the average of a nested list?

Example: Given a nested list [[1, 2, 3], [4, 5, 6]]. You want to calculate the average (1+2+3+4+5+6)/6=3.5. How do you do that?

Solution: Again, there are three solution ideas:

  • Unpack the tuple values into a list and calculate the average of this list.
  • Use only list comprehension with nested for loop.
  • Use a simple nested for loop.

Next, I’ll give all three examples in a single code snippet:

lst = [[1, 2, 3], [4, 5, 6]] # 1. Unpacking
lst_2 = [*lst[0], *lst[1]]
print(sum(lst_2) / len(lst_2))
# 3.5 # 2. List comprehension
lst_3 = [x for t in lst for x in t]
print(sum(lst_3) / len(lst_3))
# 3.5 # 3. Nested for loop
lst_4 = []
for t in lst: for x in t: lst_4.append(x)
print(sum(lst_4) / len(lst_4))
# 3.5 

Unpacking: The asterisk operator in front of an iterable “unpacks” all values in the iterable into the outer context. You can use it only in a container data structure that’s able to catch the unpacked values.

List comprehension is a compact way of creating lists. The simple formula is [ expression + context ].

  • Expression: What to do with each list element?
  • Context: What list elements to select? It consists of an arbitrary number of for and if statements.

The example [x for x in range(3)] creates the list [0, 1, 2].

Where to Go From Here

Python 3.x doesn’t have a built-in method to calculate the average. Instead, simply divide the sum of list values through the number of list elements using the two built-in functions sum() and len(). You calculate the average of a given list in Python as sum(list)/len(list). The return value is of type float.

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.

Posted on Leave a comment

100 Code Puzzles to Train Your Rapid Python Understanding

Some coders possess laser-like code understanding skills. They look at a piece of source code, and the meaning pops immediately into their great minds. If you present them with a new code snippet, they’ll tell you in a few seconds what it does.

Since I’ve started to train this skill of rapid code understanding in 2017, I’ve made rapid progress towards being able to understand source code quickly. I’ve then created the Finxter.com app with my friends Lukas and Zohaib. Since then, hundreds of thousands of students have trained their code understanding skills by solving Python code puzzles on the Finxter web app.

Many of them have surpassed our skills by a wide margin in being able to see through source code quickly.

How did they do it? And how can you do the same?

The answer is simple: you must burn the basic code patterns into your brain. If you look at a word, you don’t realize the characters anymore. The word is a single piece of information. If a chess master looks at a chess position, he doesn’t see a dozen chess pieces. The whole chess position is a single piece of information.

You can burn those code patterns into your head by solving hundreds of code puzzles that make use of similar patterns but produce different outputs. This article gives you 100 code puzzles so that you can learn this mastery skill, too.

Action steps:

  • Go over each code puzzle and take 10 seconds or so per puzzle.
  • Guess the output of the code puzzle.
  • Check your output against your guess.
  • Repeat over and over again.

Ready? So let’s start rewiring your brain cells!

(But I warn you, don’t stop solving the code puzzles just because it gets boring. The puzzles are designed to be similar so that you can understand conditional code snippets 10x faster in all your future code projects. Push through your impulse to quit until you can see the source code in a second or two.)

10 Code Puzzles With Two Variables

Let’s start slowly. Can you solve these 10 code puzzles in less than 10 minutes?

# Puzzle 0
a, b = False, True if not b and not a and a: if b: print('code') elif a and b: print('mastery') print('python')
elif a: if a and b or not b and not a: print('python') print('python')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 0: [1] Create and initialize 2 variables: a, b = False, True.
[2] Check condition (not b and not a and a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b). If it evaluates to True, print code to the shell. Otherwise, check condition (a and b). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (a). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (a and b or not b and not a). If it evaluates to True, print python to the shell. Otherwise, print python. ''' # OUTPUT: '''
python ''' # Puzzle 1
a, b = True, True if b or a and not a: if a or b: print('finxter') elif b or a: print('finxter') print('42')
elif a: if not b and b and a: print('code') print('42')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 1: [1] Create and initialize 2 variables: a, b = True, True.
[2] Check condition (b or a and not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a or b). If it evaluates to True, print finxter to the shell. Otherwise, check condition (b or a). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (a). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (not b and b and a). If it evaluates to True, print code to the shell. Otherwise, print 42. ''' # OUTPUT: '''
finxter
42 ''' # Puzzle 2
a, b = False, True if b: if not b or a or b or not a: print('finxter') elif b or not b or a: print('python') print('finxter')
elif a and b: if b and a: print('mastery') print('learn')
else: print('code') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 2: [1] Create and initialize 2 variables: a, b = False, True.
[2] Check condition (b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not b or a or b or not a). If it evaluates to True, print finxter to the shell. Otherwise, check condition (b or not b or a). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (a and b). If it evaluates to True, move on to the next step [6]. Otherwise, print code to the shell.
[6] Check condition (b and a). If it evaluates to True, print mastery to the shell. Otherwise, print learn. ''' # OUTPUT: '''
finxter
finxter ''' # Puzzle 3
a, b = True, False if not a: if a and b and not b: print('code') elif a or b: print('42') print('finxter')
elif a and not a: if b or not a and not b or a: print('learn') print('finxter')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 3: [1] Create and initialize 2 variables: a, b = True, False.
[2] Check condition (not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a and b and not b). If it evaluates to True, print code to the shell. Otherwise, check condition (a or b). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (a and not a). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (b or not a and not b or a). If it evaluates to True, print learn to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
mastery ''' # Puzzle 4
a, b = True, False if not a: if not b or a and b or not a: print('python') elif not a and a and not b: print('finxter') print('learn')
elif b or not a and not b: if b and not a and a or not b: print('finxter') print('finxter')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 4: [1] Create and initialize 2 variables: a, b = True, False.
[2] Check condition (not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not b or a and b or not a). If it evaluates to True, print python to the shell. Otherwise, check condition (not a and a and not b). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (b or not a and not b). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (b and not a and a or not b). If it evaluates to True, print finxter to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
learn ''' # Puzzle 5
a, b = True, False if b or not a or not b: if not a: print('yes') elif a: print('finxter') print('42')
elif b and not a and a: if not a or a and b: print('finxter') print('yes')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 5: [1] Create and initialize 2 variables: a, b = True, False.
[2] Check condition (b or not a or not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not a). If it evaluates to True, print yes to the shell. Otherwise, check condition (a). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (b and not a and a). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (not a or a and b). If it evaluates to True, print finxter to the shell. Otherwise, print yes. ''' # OUTPUT: '''
finxter
42 ''' # Puzzle 6
a, b = True, False if b or not b or not a and a: if not a and a or not b and b: print('love') elif a: print('yes') print('42')
elif b: if b and not b and a and not a: print('yes') print('love')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 6: [1] Create and initialize 2 variables: a, b = True, False.
[2] Check condition (b or not b or not a and a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not a and a or not b and b). If it evaluates to True, print love to the shell. Otherwise, check condition (a). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (b). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (b and not b and a and not a). If it evaluates to True, print yes to the shell. Otherwise, print love. ''' # OUTPUT: '''
yes
42 ''' # Puzzle 7
a, b = True, False if not b: if not a and b and a and not b: print('yes') elif a: print('42') print('learn')
elif a: if not b and a and b and not a: print('learn') print('finxter')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 7: [1] Create and initialize 2 variables: a, b = True, False.
[2] Check condition (not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not a and b and a and not b). If it evaluates to True, print yes to the shell. Otherwise, check condition (a). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (a). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (not b and a and b and not a). If it evaluates to True, print learn to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
42
learn ''' # Puzzle 8
a, b = False, False if a or not b: if a or b or not b: print('yes') elif b and not b: print('code') print('yes')
elif a or b or not a: if b and not b and not a and a: print('yes') print('code')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 8: [1] Create and initialize 2 variables: a, b = False, False.
[2] Check condition (a or not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a or b or not b). If it evaluates to True, print yes to the shell. Otherwise, check condition (b and not b). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (a or b or not a). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (b and not b and not a and a). If it evaluates to True, print yes to the shell. Otherwise, print code. ''' # OUTPUT: '''
yes
yes ''' # Puzzle 9
a, b = False, False if b or not b or a: if a or b and not a: print('love') elif a or not b: print('python') print('python')
elif b or not b: if b and not b or not a or a: print('learn') print('python')
else: print('code') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 9: [1] Create and initialize 2 variables: a, b = False, False.
[2] Check condition (b or not b or a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a or b and not a). If it evaluates to True, print love to the shell. Otherwise, check condition (a or not b). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (b or not b). If it evaluates to True, move on to the next step [6]. Otherwise, print code to the shell.
[6] Check condition (b and not b or not a or a). If it evaluates to True, print learn to the shell. Otherwise, print python. ''' # OUTPUT: '''
python
python '''

30 Code Puzzles With Three Variables

You’re ready for the next level. Can you solve these 30 code puzzles in less than 10 minutes? (That’s 3x the speed on a more difficult code puzzle type.)

# Puzzle 0
a, b, c = False, False, True if c: if a and b or c and not b: print('finxter') elif not a: print('mastery') print('learn')
elif a and b: if b and not c: print('python') print('love')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 0: [1] Create and initialize 3 variables: a, b, c = False, False, True.
[2] Check condition (c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a and b or c and not b). If it evaluates to True, print finxter to the shell. Otherwise, check condition (not a). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (a and b). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (b and not c). If it evaluates to True, print python to the shell. Otherwise, print love. ''' # OUTPUT: '''
finxter
learn ''' # Puzzle 1
a, b, c = False, True, True if not a or c: if a and b and c: print('finxter') elif not b or c: print('42') print('mastery')
elif b and a or c: if not a and c and a or not b: print('finxter') print('python')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 1: [1] Create and initialize 3 variables: a, b, c = False, True, True.
[2] Check condition (not a or c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a and b and c). If it evaluates to True, print finxter to the shell. Otherwise, check condition (not b or c). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (b and a or c). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (not a and c and a or not b). If it evaluates to True, print finxter to the shell. Otherwise, print python. ''' # OUTPUT: '''
42
mastery ''' # Puzzle 2
a, b, c = True, True, False if not a or not c or a: if b or c: print('learn') elif c and b or a: print('love') print('42')
elif c or b and not a: if not a: print('finxter') print('love')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 2: [1] Create and initialize 3 variables: a, b, c = True, True, False.
[2] Check condition (not a or not c or a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b or c). If it evaluates to True, print learn to the shell. Otherwise, check condition (c and b or a). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (c or b and not a). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (not a). If it evaluates to True, print finxter to the shell. Otherwise, print love. ''' # OUTPUT: '''
learn
42 ''' # Puzzle 3
a, b, c = False, True, False if c: if a: print('finxter') elif not a or b: print('learn') print('finxter')
elif not b and b: if b or c: print('learn') print('code')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 3: [1] Create and initialize 3 variables: a, b, c = False, True, False.
[2] Check condition (c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a). If it evaluates to True, print finxter to the shell. Otherwise, check condition (not a or b). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (not b and b). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (b or c). If it evaluates to True, print learn to the shell. Otherwise, print code. ''' # OUTPUT: '''
yes ''' # Puzzle 4
a, b, c = True, False, True if not c or a or not b: if b or c: print('python') elif b: print('love') print('42')
elif c and b and not c: if a or c: print('mastery') print('yes')
else: print('finxter') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 4: [1] Create and initialize 3 variables: a, b, c = True, False, True.
[2] Check condition (not c or a or not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b or c). If it evaluates to True, print python to the shell. Otherwise, check condition (b). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (c and b and not c). If it evaluates to True, move on to the next step [6]. Otherwise, print finxter to the shell.
[6] Check condition (a or c). If it evaluates to True, print mastery to the shell. Otherwise, print yes. ''' # OUTPUT: '''
python
42 ''' # Puzzle 5
a, b, c = False, True, True if c or not b or b: if c and b: print('love') elif not a or a: print('yes') print('yes')
elif a or b or not c: if not c or a and not a: print('42') print('yes')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 5: [1] Create and initialize 3 variables: a, b, c = False, True, True.
[2] Check condition (c or not b or b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c and b). If it evaluates to True, print love to the shell. Otherwise, check condition (not a or a). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (a or b or not c). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (not c or a and not a). If it evaluates to True, print 42 to the shell. Otherwise, print yes. ''' # OUTPUT: '''
love
yes ''' # Puzzle 6
a, b, c = False, False, False if a or b or not b: if a or b or c or not c: print('python') elif b: print('42') print('love')
elif b or a: if a and b and c: print('love') print('mastery')
else: print('code') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 6: [1] Create and initialize 3 variables: a, b, c = False, False, False.
[2] Check condition (a or b or not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a or b or c or not c). If it evaluates to True, print python to the shell. Otherwise, check condition (b). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (b or a). If it evaluates to True, move on to the next step [6]. Otherwise, print code to the shell.
[6] Check condition (a and b and c). If it evaluates to True, print love to the shell. Otherwise, print mastery. ''' # OUTPUT: '''
python
love ''' # Puzzle 7
a, b, c = False, True, True if b or a or not c or not b: if b or c and not b: print('love') elif a or b and not c: print('learn') print('learn')
elif b: if not b and b and a: print('mastery') print('python')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 7: [1] Create and initialize 3 variables: a, b, c = False, True, True.
[2] Check condition (b or a or not c or not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b or c and not b). If it evaluates to True, print love to the shell. Otherwise, check condition (a or b and not c). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (b). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (not b and b and a). If it evaluates to True, print mastery to the shell. Otherwise, print python. ''' # OUTPUT: '''
love
learn ''' # Puzzle 8
a, b, c = False, False, True if c and not c: if c or not c: print('learn') elif not a or b or not c: print('python') print('python')
elif a: if c or not b: print('yes') print('finxter')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 8: [1] Create and initialize 3 variables: a, b, c = False, False, True.
[2] Check condition (c and not c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c or not c). If it evaluates to True, print learn to the shell. Otherwise, check condition (not a or b or not c). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (a). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (c or not b). If it evaluates to True, print yes to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
42 ''' # Puzzle 9
a, b, c = True, False, True if c: if not b or b and not c: print('finxter') elif c and not b: print('python') print('code')
elif not b or b and c: if not a and a: print('mastery') print('python')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 9: [1] Create and initialize 3 variables: a, b, c = True, False, True.
[2] Check condition (c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not b or b and not c). If it evaluates to True, print finxter to the shell. Otherwise, check condition (c and not b). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print code to the shell.
[5] Check the elif condition (not b or b and c). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (not a and a). If it evaluates to True, print mastery to the shell. Otherwise, print python. ''' # OUTPUT: '''
finxter
code ''' # Puzzle 10
a, b, c = True, False, False if not b and c: if a or not c or b: print('learn') elif a: print('yes') print('love')
elif not b or c or not c: if c and not a and b: print('finxter') print('learn')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 10: [1] Create and initialize 3 variables: a, b, c = True, False, False.
[2] Check condition (not b and c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a or not c or b). If it evaluates to True, print learn to the shell. Otherwise, check condition (a). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (not b or c or not c). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (c and not a and b). If it evaluates to True, print finxter to the shell. Otherwise, print learn. ''' # OUTPUT: '''
learn ''' # Puzzle 11
a, b, c = False, False, True if c and not c and b: if not a and b: print('code') elif not a or a and not b: print('42') print('yes')
elif b: if not b and b or a: print('yes') print('learn')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 11: [1] Create and initialize 3 variables: a, b, c = False, False, True.
[2] Check condition (c and not c and b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not a and b). If it evaluates to True, print code to the shell. Otherwise, check condition (not a or a and not b). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (b). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (not b and b or a). If it evaluates to True, print yes to the shell. Otherwise, print learn. ''' # OUTPUT: '''
python ''' # Puzzle 12
a, b, c = False, False, True if a and c or b: if b and c: print('mastery') elif b: print('python') print('love')
elif c or a and not c: if b and c and not c and a: print('yes') print('42')
else: print('finxter') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 12: [1] Create and initialize 3 variables: a, b, c = False, False, True.
[2] Check condition (a and c or b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b and c). If it evaluates to True, print mastery to the shell. Otherwise, check condition (b). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (c or a and not c). If it evaluates to True, move on to the next step [6]. Otherwise, print finxter to the shell.
[6] Check condition (b and c and not c and a). If it evaluates to True, print yes to the shell. Otherwise, print 42. ''' # OUTPUT: '''
42 ''' # Puzzle 13
a, b, c = False, True, True if b: if a and b and c or not c: print('learn') elif not c and a and c: print('42') print('mastery')
elif b or c and a: if c or b and not b: print('finxter') print('learn')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 13: [1] Create and initialize 3 variables: a, b, c = False, True, True.
[2] Check condition (b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a and b and c or not c). If it evaluates to True, print learn to the shell. Otherwise, check condition (not c and a and c). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (b or c and a). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (c or b and not b). If it evaluates to True, print finxter to the shell. Otherwise, print learn. ''' # OUTPUT: '''
mastery ''' # Puzzle 14
a, b, c = True, True, True if a and c and not a and b: if not c and a or not a: print('42') elif b: print('python') print('mastery')
elif b and c or not b: if c or not a or a and b: print('love') print('learn')
else: print('finxter') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 14: [1] Create and initialize 3 variables: a, b, c = True, True, True.
[2] Check condition (a and c and not a and b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not c and a or not a). If it evaluates to True, print 42 to the shell. Otherwise, check condition (b). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (b and c or not b). If it evaluates to True, move on to the next step [6]. Otherwise, print finxter to the shell.
[6] Check condition (c or not a or a and b). If it evaluates to True, print love to the shell. Otherwise, print learn. ''' # OUTPUT: '''
love
learn ''' # Puzzle 15
a, b, c = True, True, False if a and c and b and not c: if c: print('finxter') elif b or c and a: print('learn') print('code')
elif not c: if not c and b and a: print('learn') print('yes')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 15: [1] Create and initialize 3 variables: a, b, c = True, True, False.
[2] Check condition (a and c and b and not c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c). If it evaluates to True, print finxter to the shell. Otherwise, check condition (b or c and a). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print code to the shell.
[5] Check the elif condition (not c). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (not c and b and a). If it evaluates to True, print learn to the shell. Otherwise, print yes. ''' # OUTPUT: '''
learn
yes ''' # Puzzle 16
a, b, c = True, False, True if c or not b: if b or c and a and not b: print('learn') elif c or a or b: print('42') print('code')
elif c: if a: print('yes') print('love')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 16: [1] Create and initialize 3 variables: a, b, c = True, False, True.
[2] Check condition (c or not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b or c and a and not b). If it evaluates to True, print learn to the shell. Otherwise, check condition (c or a or b). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print code to the shell.
[5] Check the elif condition (c). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (a). If it evaluates to True, print yes to the shell. Otherwise, print love. ''' # OUTPUT: '''
learn
code ''' # Puzzle 17
a, b, c = True, False, False if a: if b and c or not c or a: print('code') elif a or not b or not c: print('love') print('learn')
elif a or c: if not b: print('finxter') print('love')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 17: [1] Create and initialize 3 variables: a, b, c = True, False, False.
[2] Check condition (a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b and c or not c or a). If it evaluates to True, print code to the shell. Otherwise, check condition (a or not b or not c). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (a or c). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (not b). If it evaluates to True, print finxter to the shell. Otherwise, print love. ''' # OUTPUT: '''
code
learn ''' # Puzzle 18
a, b, c = False, True, True if a and b and not b and c: if b or c: print('code') elif c and not b and b: print('42') print('code')
elif c or not c: if a or not b or b and not a: print('mastery') print('42')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 18: [1] Create and initialize 3 variables: a, b, c = False, True, True.
[2] Check condition (a and b and not b and c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b or c). If it evaluates to True, print code to the shell. Otherwise, check condition (c and not b and b). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print code to the shell.
[5] Check the elif condition (c or not c). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (a or not b or b and not a). If it evaluates to True, print mastery to the shell. Otherwise, print 42. ''' # OUTPUT: '''
mastery
42 ''' # Puzzle 19
a, b, c = False, False, False if b and not c: if c or b or not c or a: print('love') elif c and a: print('love') print('code')
elif not b: if b or c: print('code') print('learn')
else: print('code') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 19: [1] Create and initialize 3 variables: a, b, c = False, False, False.
[2] Check condition (b and not c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c or b or not c or a). If it evaluates to True, print love to the shell. Otherwise, check condition (c and a). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print code to the shell.
[5] Check the elif condition (not b). If it evaluates to True, move on to the next step [6]. Otherwise, print code to the shell.
[6] Check condition (b or c). If it evaluates to True, print code to the shell. Otherwise, print learn. ''' # OUTPUT: '''
learn ''' # Puzzle 20
a, b, c = True, False, False if c or a and b or not a: if a and b and c: print('finxter') elif not a: print('code') print('42')
elif c and a or b: if a or not c or c or not a: print('learn') print('mastery')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 20: [1] Create and initialize 3 variables: a, b, c = True, False, False.
[2] Check condition (c or a and b or not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a and b and c). If it evaluates to True, print finxter to the shell. Otherwise, check condition (not a). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (c and a or b). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (a or not c or c or not a). If it evaluates to True, print learn to the shell. Otherwise, print mastery. ''' # OUTPUT: '''
42 ''' # Puzzle 21
a, b, c = False, True, False if a: if c or a and b: print('code') elif b or not c: print('python') print('love')
elif c and a: if c or b or a and not a: print('code') print('42')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 21: [1] Create and initialize 3 variables: a, b, c = False, True, False.
[2] Check condition (a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c or a and b). If it evaluates to True, print code to the shell. Otherwise, check condition (b or not c). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (c and a). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (c or b or a and not a). If it evaluates to True, print code to the shell. Otherwise, print 42. ''' # OUTPUT: '''
python ''' # Puzzle 22
a, b, c = True, False, True if a: if a or b: print('love') elif not c and b: print('yes') print('yes')
elif not b and not a or c: if not a and b: print('love') print('code')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 22: [1] Create and initialize 3 variables: a, b, c = True, False, True.
[2] Check condition (a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a or b). If it evaluates to True, print love to the shell. Otherwise, check condition (not c and b). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (not b and not a or c). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (not a and b). If it evaluates to True, print love to the shell. Otherwise, print code. ''' # OUTPUT: '''
love
yes ''' # Puzzle 23
a, b, c = False, True, False if b and a: if a: print('code') elif c and b: print('learn') print('42')
elif c: if b and a or not a: print('python') print('love')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 23: [1] Create and initialize 3 variables: a, b, c = False, True, False.
[2] Check condition (b and a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a). If it evaluates to True, print code to the shell. Otherwise, check condition (c and b). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (c). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (b and a or not a). If it evaluates to True, print python to the shell. Otherwise, print love. ''' # OUTPUT: '''
mastery ''' # Puzzle 24
a, b, c = False, False, False if not a: if a and not b and c: print('learn') elif b or c: print('love') print('love')
elif a or not b or b: if not b and c: print('mastery') print('42')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 24: [1] Create and initialize 3 variables: a, b, c = False, False, False.
[2] Check condition (not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a and not b and c). If it evaluates to True, print learn to the shell. Otherwise, check condition (b or c). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (a or not b or b). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (not b and c). If it evaluates to True, print mastery to the shell. Otherwise, print 42. ''' # OUTPUT: '''
love ''' # Puzzle 25
a, b, c = True, True, False if not a: if a or b: print('code') elif a and c: print('yes') print('yes')
elif b: if not c or b or a and c: print('love') print('learn')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 25: [1] Create and initialize 3 variables: a, b, c = True, True, False.
[2] Check condition (not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a or b). If it evaluates to True, print code to the shell. Otherwise, check condition (a and c). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (b). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (not c or b or a and c). If it evaluates to True, print love to the shell. Otherwise, print learn. ''' # OUTPUT: '''
love
learn ''' # Puzzle 26
a, b, c = True, False, False if not a: if b or c and not c: print('love') elif a and b or c: print('love') print('42')
elif not b and c: if a: print('code') print('finxter')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 26: [1] Create and initialize 3 variables: a, b, c = True, False, False.
[2] Check condition (not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b or c and not c). If it evaluates to True, print love to the shell. Otherwise, check condition (a and b or c). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (not b and c). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (a). If it evaluates to True, print code to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
mastery ''' # Puzzle 27
a, b, c = False, True, False if not b and not a and b and a: if a or c or b or not c: print('learn') elif b or not b or c: print('mastery') print('learn')
elif a and b: if a: print('finxter') print('learn')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 27: [1] Create and initialize 3 variables: a, b, c = False, True, False.
[2] Check condition (not b and not a and b and a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a or c or b or not c). If it evaluates to True, print learn to the shell. Otherwise, check condition (b or not b or c). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (a and b). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (a). If it evaluates to True, print finxter to the shell. Otherwise, print learn. ''' # OUTPUT: '''
learn ''' # Puzzle 28
a, b, c = False, True, False if not c and a and b or not a: if not b or a or not c: print('mastery') elif not b or c and b: print('code') print('42')
elif b: if c or not c and not a: print('love') print('yes')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 28: [1] Create and initialize 3 variables: a, b, c = False, True, False.
[2] Check condition (not c and a and b or not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not b or a or not c). If it evaluates to True, print mastery to the shell. Otherwise, check condition (not b or c and b). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (b). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (c or not c and not a). If it evaluates to True, print love to the shell. Otherwise, print yes. ''' # OUTPUT: '''
mastery
42 ''' # Puzzle 29
a, b, c = True, False, False if a: if c or a: print('42') elif a: print('code') print('code')
elif c and not a and b: if b or a: print('python') print('learn')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 29: [1] Create and initialize 3 variables: a, b, c = True, False, False.
[2] Check condition (a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c or a). If it evaluates to True, print 42 to the shell. Otherwise, check condition (a). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print code to the shell.
[5] Check the elif condition (c and not a and b). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (b or a). If it evaluates to True, print python to the shell. Otherwise, print learn. ''' # OUTPUT: '''
42
code '''

30 Code Puzzles with Four Variables

Wow, this was harder, wasn’t it? But now you’re ready to solve these 30 code puzzles in less than 10 minutes, aren’t you? (Same speed as before but higher complexity.)

# Puzzle 0
a, b, c, d = False, False, False, True if d and c and not d and b: if d or not a: print('learn') elif c: print('yes') print('python')
elif not a or d: if not a: print('finxter') print('python')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 0: [1] Create and initialize 4 variables: a, b, c, d = False, False, False, True.
[2] Check condition (d and c and not d and b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d or not a). If it evaluates to True, print learn to the shell. Otherwise, check condition (c). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (not a or d). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (not a). If it evaluates to True, print finxter to the shell. Otherwise, print python. ''' # OUTPUT: '''
finxter
python ''' # Puzzle 1
a, b, c, d = True, True, True, True if not c: if not b or c: print('yes') elif b or not d or a: print('finxter') print('mastery')
elif not d: if d or b: print('finxter') print('mastery')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 1: [1] Create and initialize 4 variables: a, b, c, d = True, True, True, True.
[2] Check condition (not c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not b or c). If it evaluates to True, print yes to the shell. Otherwise, check condition (b or not d or a). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (not d). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (d or b). If it evaluates to True, print finxter to the shell. Otherwise, print mastery. ''' # OUTPUT: '''
42 ''' # Puzzle 2
a, b, c, d = True, True, False, True if a: if not d and not a and d or not c: print('finxter') elif not b or a and b: print('finxter') print('learn')
elif c and not d: if b or not b and not a or a: print('learn') print('love')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 2: [1] Create and initialize 4 variables: a, b, c, d = True, True, False, True.
[2] Check condition (a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not d and not a and d or not c). If it evaluates to True, print finxter to the shell. Otherwise, check condition (not b or a and b). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (c and not d). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (b or not b and not a or a). If it evaluates to True, print learn to the shell. Otherwise, print love. ''' # OUTPUT: '''
finxter
learn ''' # Puzzle 3
a, b, c, d = False, False, False, False if a and d and not b and c: if a: print('yes') elif d and a: print('love') print('learn')
elif a and c or b: if d or b or not b: print('yes') print('finxter')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 3: [1] Create and initialize 4 variables: a, b, c, d = False, False, False, False.
[2] Check condition (a and d and not b and c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a). If it evaluates to True, print yes to the shell. Otherwise, check condition (d and a). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (a and c or b). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (d or b or not b). If it evaluates to True, print yes to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
python ''' # Puzzle 4
a, b, c, d = True, False, True, False if not d or d: if not d and not b or b or d: print('code') elif c or d: print('python') print('learn')
elif b and c: if a or d or b and c: print('finxter') print('python')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 4: [1] Create and initialize 4 variables: a, b, c, d = True, False, True, False.
[2] Check condition (not d or d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not d and not b or b or d). If it evaluates to True, print code to the shell. Otherwise, check condition (c or d). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (b and c). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (a or d or b and c). If it evaluates to True, print finxter to the shell. Otherwise, print python. ''' # OUTPUT: '''
code
learn ''' # Puzzle 5
a, b, c, d = False, False, False, False if not d or d or a or b: if b: print('yes') elif a and not b: print('42') print('love')
elif c and not b: if b and not d and not b: print('yes') print('yes')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 5: [1] Create and initialize 4 variables: a, b, c, d = False, False, False, False.
[2] Check condition (not d or d or a or b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b). If it evaluates to True, print yes to the shell. Otherwise, check condition (a and not b). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (c and not b). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (b and not d and not b). If it evaluates to True, print yes to the shell. Otherwise, print yes. ''' # OUTPUT: '''
love ''' # Puzzle 6
a, b, c, d = True, False, True, False if c or not a: if b and d: print('python') elif a or d and c: print('love') print('yes')
elif c: if not d and b or c: print('love') print('code')
else: print('code') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 6: [1] Create and initialize 4 variables: a, b, c, d = True, False, True, False.
[2] Check condition (c or not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b and d). If it evaluates to True, print python to the shell. Otherwise, check condition (a or d and c). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (c). If it evaluates to True, move on to the next step [6]. Otherwise, print code to the shell.
[6] Check condition (not d and b or c). If it evaluates to True, print love to the shell. Otherwise, print code. ''' # OUTPUT: '''
love
yes ''' # Puzzle 7
a, b, c, d = False, True, False, True if not c or b and a and c: if c or not c or b and a: print('42') elif d and not d: print('code') print('mastery')
elif c or not c and a: if b: print('42') print('code')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 7: [1] Create and initialize 4 variables: a, b, c, d = False, True, False, True.
[2] Check condition (not c or b and a and c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c or not c or b and a). If it evaluates to True, print 42 to the shell. Otherwise, check condition (d and not d). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (c or not c and a). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (b). If it evaluates to True, print 42 to the shell. Otherwise, print code. ''' # OUTPUT: '''
42
mastery ''' # Puzzle 8
a, b, c, d = True, True, False, True if a or c and d or not a: if not d: print('learn') elif c or d: print('learn') print('love')
elif a: if d: print('yes') print('42')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 8: [1] Create and initialize 4 variables: a, b, c, d = True, True, False, True.
[2] Check condition (a or c and d or not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not d). If it evaluates to True, print learn to the shell. Otherwise, check condition (c or d). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (a). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (d). If it evaluates to True, print yes to the shell. Otherwise, print 42. ''' # OUTPUT: '''
learn
love ''' # Puzzle 9
a, b, c, d = False, False, False, True if c: if not c and b: print('python') elif a: print('mastery') print('mastery')
elif c or a: if c: print('finxter') print('code')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 9: [1] Create and initialize 4 variables: a, b, c, d = False, False, False, True.
[2] Check condition (c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not c and b). If it evaluates to True, print python to the shell. Otherwise, check condition (a). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (c or a). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (c). If it evaluates to True, print finxter to the shell. Otherwise, print code. ''' # OUTPUT: '''
love ''' # Puzzle 10
a, b, c, d = False, False, True, True if not c and b and d: if not c: print('mastery') elif not b or not a or c: print('learn') print('learn')
elif c or b and d: if a or c or b and d: print('finxter') print('python')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 10: [1] Create and initialize 4 variables: a, b, c, d = False, False, True, True.
[2] Check condition (not c and b and d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not c). If it evaluates to True, print mastery to the shell. Otherwise, check condition (not b or not a or c). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (c or b and d). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (a or c or b and d). If it evaluates to True, print finxter to the shell. Otherwise, print python. ''' # OUTPUT: '''
finxter
python ''' # Puzzle 11
a, b, c, d = False, False, True, False if b or a: if b: print('finxter') elif a or d or not c: print('finxter') print('42')
elif not b: if a and c or b: print('code') print('code')
else: print('code') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 11: [1] Create and initialize 4 variables: a, b, c, d = False, False, True, False.
[2] Check condition (b or a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b). If it evaluates to True, print finxter to the shell. Otherwise, check condition (a or d or not c). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (not b). If it evaluates to True, move on to the next step [6]. Otherwise, print code to the shell.
[6] Check condition (a and c or b). If it evaluates to True, print code to the shell. Otherwise, print code. ''' # OUTPUT: '''
code ''' # Puzzle 12
a, b, c, d = True, True, False, True if c: if b and d: print('42') elif c or d or a: print('42') print('42')
elif d or b or not d: if c: print('finxter') print('python')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 12: [1] Create and initialize 4 variables: a, b, c, d = True, True, False, True.
[2] Check condition (c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b and d). If it evaluates to True, print 42 to the shell. Otherwise, check condition (c or d or a). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (d or b or not d). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (c). If it evaluates to True, print finxter to the shell. Otherwise, print python. ''' # OUTPUT: '''
python ''' # Puzzle 13
a, b, c, d = False, True, False, False if a and b or not d and not b: if d and b and not c or a: print('finxter') elif a or not c: print('code') print('yes')
elif c: if not b: print('finxter') print('python')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 13: [1] Create and initialize 4 variables: a, b, c, d = False, True, False, False.
[2] Check condition (a and b or not d and not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d and b and not c or a). If it evaluates to True, print finxter to the shell. Otherwise, check condition (a or not c). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (c). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (not b). If it evaluates to True, print finxter to the shell. Otherwise, print python. ''' # OUTPUT: '''
mastery ''' # Puzzle 14
a, b, c, d = True, True, True, True if d or not b or b: if not c or c and not d: print('love') elif not d and b or a: print('mastery') print('mastery')
elif not c or a: if d and b and c and not d: print('code') print('mastery')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 14: [1] Create and initialize 4 variables: a, b, c, d = True, True, True, True.
[2] Check condition (d or not b or b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not c or c and not d). If it evaluates to True, print love to the shell. Otherwise, check condition (not d and b or a). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (not c or a). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (d and b and c and not d). If it evaluates to True, print code to the shell. Otherwise, print mastery. ''' # OUTPUT: '''
mastery
mastery ''' # Puzzle 15
a, b, c, d = True, True, True, False if d and not c: if d and c and not d or b: print('code') elif not b or not c or a: print('code') print('learn')
elif not c: if a and c and b or not d: print('python') print('python')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 15: [1] Create and initialize 4 variables: a, b, c, d = True, True, True, False.
[2] Check condition (d and not c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d and c and not d or b). If it evaluates to True, print code to the shell. Otherwise, check condition (not b or not c or a). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (not c). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (a and c and b or not d). If it evaluates to True, print python to the shell. Otherwise, print python. ''' # OUTPUT: '''
mastery ''' # Puzzle 16
a, b, c, d = True, False, False, True if c: if b and c or not c or not d: print('mastery') elif c or d or not b: print('code') print('python')
elif b or d and not c: if c or b or a: print('finxter') print('code')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 16: [1] Create and initialize 4 variables: a, b, c, d = True, False, False, True.
[2] Check condition (c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b and c or not c or not d). If it evaluates to True, print mastery to the shell. Otherwise, check condition (c or d or not b). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (b or d and not c). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (c or b or a). If it evaluates to True, print finxter to the shell. Otherwise, print code. ''' # OUTPUT: '''
finxter
code ''' # Puzzle 17
a, b, c, d = False, False, True, False if c and a: if c: print('love') elif d or a: print('code') print('finxter')
elif a or c and not c: if d: print('mastery') print('mastery')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 17: [1] Create and initialize 4 variables: a, b, c, d = False, False, True, False.
[2] Check condition (c and a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c). If it evaluates to True, print love to the shell. Otherwise, check condition (d or a). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (a or c and not c). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (d). If it evaluates to True, print mastery to the shell. Otherwise, print mastery. ''' # OUTPUT: '''
love ''' # Puzzle 18
a, b, c, d = True, True, False, False if d or b: if not d or c: print('42') elif not a and d: print('code') print('finxter')
elif not b: if d and c: print('code') print('love')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 18: [1] Create and initialize 4 variables: a, b, c, d = True, True, False, False.
[2] Check condition (d or b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not d or c). If it evaluates to True, print 42 to the shell. Otherwise, check condition (not a and d). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (not b). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (d and c). If it evaluates to True, print code to the shell. Otherwise, print love. ''' # OUTPUT: '''
42
finxter ''' # Puzzle 19
a, b, c, d = True, False, False, False if b and d and not d or not b: if not b or c: print('code') elif d or c: print('yes') print('love')
elif d: if c and a: print('42') print('love')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 19: [1] Create and initialize 4 variables: a, b, c, d = True, False, False, False.
[2] Check condition (b and d and not d or not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not b or c). If it evaluates to True, print code to the shell. Otherwise, check condition (d or c). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (d). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (c and a). If it evaluates to True, print 42 to the shell. Otherwise, print love. ''' # OUTPUT: '''
code
love ''' # Puzzle 20
a, b, c, d = True, True, False, False if not a or d or a or c: if c: print('42') elif d or c and not c: print('mastery') print('code')
elif d or not b or b: if a: print('mastery') print('python')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 20: [1] Create and initialize 4 variables: a, b, c, d = True, True, False, False.
[2] Check condition (not a or d or a or c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c). If it evaluates to True, print 42 to the shell. Otherwise, check condition (d or c and not c). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print code to the shell.
[5] Check the elif condition (d or not b or b). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (a). If it evaluates to True, print mastery to the shell. Otherwise, print python. ''' # OUTPUT: '''
code ''' # Puzzle 21
a, b, c, d = False, True, False, False if d and a and b: if a: print('finxter') elif b and not b: print('yes') print('learn')
elif not c and d or c: if a: print('yes') print('code')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 21: [1] Create and initialize 4 variables: a, b, c, d = False, True, False, False.
[2] Check condition (d and a and b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a). If it evaluates to True, print finxter to the shell. Otherwise, check condition (b and not b). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (not c and d or c). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (a). If it evaluates to True, print yes to the shell. Otherwise, print code. ''' # OUTPUT: '''
love ''' # Puzzle 22
a, b, c, d = True, False, True, False if not b and a and d or b: if d: print('42') elif not a or c: print('mastery') print('finxter')
elif b or d: if a or c or not d and d: print('code') print('42')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 22: [1] Create and initialize 4 variables: a, b, c, d = True, False, True, False.
[2] Check condition (not b and a and d or b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d). If it evaluates to True, print 42 to the shell. Otherwise, check condition (not a or c). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (b or d). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (a or c or not d and d). If it evaluates to True, print code to the shell. Otherwise, print 42. ''' # OUTPUT: '''
mastery ''' # Puzzle 23
a, b, c, d = False, True, False, False if not a: if b and d or a: print('yes') elif c and not c: print('love') print('mastery')
elif b or d: if not a and b or not d: print('yes') print('learn')
else: print('code') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 23: [1] Create and initialize 4 variables: a, b, c, d = False, True, False, False.
[2] Check condition (not a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b and d or a). If it evaluates to True, print yes to the shell. Otherwise, check condition (c and not c). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (b or d). If it evaluates to True, move on to the next step [6]. Otherwise, print code to the shell.
[6] Check condition (not a and b or not d). If it evaluates to True, print yes to the shell. Otherwise, print learn. ''' # OUTPUT: '''
mastery ''' # Puzzle 24
a, b, c, d = True, True, False, True if a or not a or d or c: if b: print('42') elif d or a: print('love') print('42')
elif b and a: if b and a or d and not c: print('42') print('yes')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 24: [1] Create and initialize 4 variables: a, b, c, d = True, True, False, True.
[2] Check condition (a or not a or d or c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b). If it evaluates to True, print 42 to the shell. Otherwise, check condition (d or a). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (b and a). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (b and a or d and not c). If it evaluates to True, print 42 to the shell. Otherwise, print yes. ''' # OUTPUT: '''
42
42 ''' # Puzzle 25
a, b, c, d = True, True, True, False if a: if not a and a or b: print('42') elif a and d and c: print('python') print('learn')
elif d and not c: if not b: print('mastery') print('code')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 25: [1] Create and initialize 4 variables: a, b, c, d = True, True, True, False.
[2] Check condition (a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not a and a or b). If it evaluates to True, print 42 to the shell. Otherwise, check condition (a and d and c). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (d and not c). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (not b). If it evaluates to True, print mastery to the shell. Otherwise, print code. ''' # OUTPUT: '''
42
learn ''' # Puzzle 26
a, b, c, d = True, False, False, False if c: if d and not a and not b or not d: print('mastery') elif d: print('finxter') print('learn')
elif not a: if a and not b and d: print('python') print('love')
else: print('code') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 26: [1] Create and initialize 4 variables: a, b, c, d = True, False, False, False.
[2] Check condition (c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d and not a and not b or not d). If it evaluates to True, print mastery to the shell. Otherwise, check condition (d). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (not a). If it evaluates to True, move on to the next step [6]. Otherwise, print code to the shell.
[6] Check condition (a and not b and d). If it evaluates to True, print python to the shell. Otherwise, print love. ''' # OUTPUT: '''
code ''' # Puzzle 27
a, b, c, d = True, True, False, False if b and not a or d: if not a and c and d: print('42') elif c: print('yes') print('python')
elif not b and c: if not d and b or not a and c: print('love') print('learn')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 27: [1] Create and initialize 4 variables: a, b, c, d = True, True, False, False.
[2] Check condition (b and not a or d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not a and c and d). If it evaluates to True, print 42 to the shell. Otherwise, check condition (c). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (not b and c). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (not d and b or not a and c). If it evaluates to True, print love to the shell. Otherwise, print learn. ''' # OUTPUT: '''
python ''' # Puzzle 28
a, b, c, d = False, False, True, False if d or a and not a and not b: if d or not b: print('python') elif d and c and b: print('finxter') print('python')
elif a and b: if b and not b or c or d: print('42') print('yes')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 28: [1] Create and initialize 4 variables: a, b, c, d = False, False, True, False.
[2] Check condition (d or a and not a and not b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d or not b). If it evaluates to True, print python to the shell. Otherwise, check condition (d and c and b). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (a and b). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (b and not b or c or d). If it evaluates to True, print 42 to the shell. Otherwise, print yes. ''' # OUTPUT: '''
love ''' # Puzzle 29
a, b, c, d = False, True, True, False if a and not b and d: if a and not a: print('love') elif c and not b: print('code') print('python')
elif c and a: if not c: print('42') print('finxter')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 29: [1] Create and initialize 4 variables: a, b, c, d = False, True, True, False.
[2] Check condition (a and not b and d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a and not a). If it evaluates to True, print love to the shell. Otherwise, check condition (c and not b). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (c and a). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (not c). If it evaluates to True, print 42 to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
learn '''

30 Code Puzzles with Five Variables

To be frank, I didn’t expect you make it that far. Are you ready for the final 30 code puzzles in 10 minutes? (Same speed as before but higher complexity.)

# Puzzle 0
a, b, c, d, e = False, True, False, False, True if e: if not c or e and not d or not e: print('mastery') elif d and a and c: print('learn') print('mastery')
elif d and not d or a: if b or c or a: print('learn') print('finxter')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 0: [1] Create and initialize 5 variables: a, b, c, d, e = False, True, False, False, True.
[2] Check condition (e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not c or e and not d or not e). If it evaluates to True, print mastery to the shell. Otherwise, check condition (d and a and c). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (d and not d or a). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (b or c or a). If it evaluates to True, print learn to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
mastery
mastery ''' # Puzzle 1
a, b, c, d, e = True, False, False, False, False if a and b: if b or d and not b: print('yes') elif c: print('42') print('42')
elif b or a: if not c or c and not e or a: print('42') print('code')
else: print('finxter') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 1: [1] Create and initialize 5 variables: a, b, c, d, e = True, False, False, False, False.
[2] Check condition (a and b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b or d and not b). If it evaluates to True, print yes to the shell. Otherwise, check condition (c). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (b or a). If it evaluates to True, move on to the next step [6]. Otherwise, print finxter to the shell.
[6] Check condition (not c or c and not e or a). If it evaluates to True, print 42 to the shell. Otherwise, print code. ''' # OUTPUT: '''
42
code ''' # Puzzle 2
a, b, c, d, e = True, True, False, True, True if not a or d and e and not e: if c and e and not b: print('learn') elif e or b or d: print('42') print('yes')
elif not d and c: if b: print('yes') print('mastery')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 2: [1] Create and initialize 5 variables: a, b, c, d, e = True, True, False, True, True.
[2] Check condition (not a or d and e and not e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c and e and not b). If it evaluates to True, print learn to the shell. Otherwise, check condition (e or b or d). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (not d and c). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (b). If it evaluates to True, print yes to the shell. Otherwise, print mastery. ''' # OUTPUT: '''
42 ''' # Puzzle 3
a, b, c, d, e = False, True, True, True, False if d and c or a or b: if d and e: print('learn') elif a or e: print('finxter') print('yes')
elif d: if e and b: print('python') print('42')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 3: [1] Create and initialize 5 variables: a, b, c, d, e = False, True, True, True, False.
[2] Check condition (d and c or a or b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d and e). If it evaluates to True, print learn to the shell. Otherwise, check condition (a or e). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (d). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (e and b). If it evaluates to True, print python to the shell. Otherwise, print 42. ''' # OUTPUT: '''
yes ''' # Puzzle 4
a, b, c, d, e = True, False, False, True, False if b or not b or not c: if e and b and not b and d: print('42') elif not b or b and not c: print('python') print('python')
elif d and e: if a: print('mastery') print('love')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 4: [1] Create and initialize 5 variables: a, b, c, d, e = True, False, False, True, False.
[2] Check condition (b or not b or not c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (e and b and not b and d). If it evaluates to True, print 42 to the shell. Otherwise, check condition (not b or b and not c). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (d and e). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (a). If it evaluates to True, print mastery to the shell. Otherwise, print love. ''' # OUTPUT: '''
python
python ''' # Puzzle 5
a, b, c, d, e = True, False, True, True, False if c: if a: print('learn') elif not e: print('code') print('love')
elif a or e: if e: print('42') print('code')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 5: [1] Create and initialize 5 variables: a, b, c, d, e = True, False, True, True, False.
[2] Check condition (c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a). If it evaluates to True, print learn to the shell. Otherwise, check condition (not e). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (a or e). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (e). If it evaluates to True, print 42 to the shell. Otherwise, print code. ''' # OUTPUT: '''
learn
love ''' # Puzzle 6
a, b, c, d, e = False, False, False, True, False if not e: if e and d and b or c: print('code') elif c or not a and a: print('42') print('code')
elif c or b: if c: print('yes') print('code')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 6: [1] Create and initialize 5 variables: a, b, c, d, e = False, False, False, True, False.
[2] Check condition (not e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (e and d and b or c). If it evaluates to True, print code to the shell. Otherwise, check condition (c or not a and a). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print code to the shell.
[5] Check the elif condition (c or b). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (c). If it evaluates to True, print yes to the shell. Otherwise, print code. ''' # OUTPUT: '''
code ''' # Puzzle 7
a, b, c, d, e = True, False, False, False, False if b and not b and not c and not e: if b or not d or c: print('mastery') elif a and b and e: print('mastery') print('yes')
elif not a and not e or e: if c or a or not d or not a: print('42') print('python')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 7: [1] Create and initialize 5 variables: a, b, c, d, e = True, False, False, False, False.
[2] Check condition (b and not b and not c and not e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b or not d or c). If it evaluates to True, print mastery to the shell. Otherwise, check condition (a and b and e). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print yes to the shell.
[5] Check the elif condition (not a and not e or e). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (c or a or not d or not a). If it evaluates to True, print 42 to the shell. Otherwise, print python. ''' # OUTPUT: '''
yes ''' # Puzzle 8
a, b, c, d, e = True, True, False, True, False if not c or a or not b and d: if not b or not e or d and not a: print('yes') elif a or e: print('mastery') print('love')
elif not b and c: if a and d or e and c: print('finxter') print('yes')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 8: [1] Create and initialize 5 variables: a, b, c, d, e = True, True, False, True, False.
[2] Check condition (not c or a or not b and d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not b or not e or d and not a). If it evaluates to True, print yes to the shell. Otherwise, check condition (a or e). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (not b and c). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (a and d or e and c). If it evaluates to True, print finxter to the shell. Otherwise, print yes. ''' # OUTPUT: '''
yes
love ''' # Puzzle 9
a, b, c, d, e = False, True, True, True, False if not b and b and a: if a: print('mastery') elif e or a: print('code') print('learn')
elif e and b or c: if b and c: print('mastery') print('learn')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 9: [1] Create and initialize 5 variables: a, b, c, d, e = False, True, True, True, False.
[2] Check condition (not b and b and a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a). If it evaluates to True, print mastery to the shell. Otherwise, check condition (e or a). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (e and b or c). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (b and c). If it evaluates to True, print mastery to the shell. Otherwise, print learn. ''' # OUTPUT: '''
mastery
learn ''' # Puzzle 10
a, b, c, d, e = False, True, False, True, False if not e and b and d: if not c: print('finxter') elif not e: print('python') print('love')
elif e: if a or not a: print('python') print('finxter')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 10: [1] Create and initialize 5 variables: a, b, c, d, e = False, True, False, True, False.
[2] Check condition (not e and b and d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not c). If it evaluates to True, print finxter to the shell. Otherwise, check condition (not e). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (e). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (a or not a). If it evaluates to True, print python to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
finxter
love ''' # Puzzle 11
a, b, c, d, e = True, False, True, False, True if e: if not c or not a or b: print('mastery') elif c or d: print('finxter') print('python')
elif c: if not b or a: print('learn') print('code')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 11: [1] Create and initialize 5 variables: a, b, c, d, e = True, False, True, False, True.
[2] Check condition (e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not c or not a or b). If it evaluates to True, print mastery to the shell. Otherwise, check condition (c or d). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (c). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (not b or a). If it evaluates to True, print learn to the shell. Otherwise, print code. ''' # OUTPUT: '''
finxter
python ''' # Puzzle 12
a, b, c, d, e = False, False, False, True, True if b and d: if not e: print('yes') elif b or c or not a: print('code') print('love')
elif not a: if not e and not b and d and a: print('python') print('code')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 12: [1] Create and initialize 5 variables: a, b, c, d, e = False, False, False, True, True.
[2] Check condition (b and d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not e). If it evaluates to True, print yes to the shell. Otherwise, check condition (b or c or not a). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (not a). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (not e and not b and d and a). If it evaluates to True, print python to the shell. Otherwise, print code. ''' # OUTPUT: '''
code ''' # Puzzle 13
a, b, c, d, e = False, True, True, False, True if d: if b or c and e: print('finxter') elif d or not b or e: print('learn') print('learn')
elif c and b and e: if not d or e and c and a: print('code') print('mastery')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 13: [1] Create and initialize 5 variables: a, b, c, d, e = False, True, True, False, True.
[2] Check condition (d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b or c and e). If it evaluates to True, print finxter to the shell. Otherwise, check condition (d or not b or e). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (c and b and e). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (not d or e and c and a). If it evaluates to True, print code to the shell. Otherwise, print mastery. ''' # OUTPUT: '''
code
mastery ''' # Puzzle 14
a, b, c, d, e = False, False, False, False, False if c and not b or a and not d: if d or b and not c or a: print('finxter') elif d and a: print('42') print('learn')
elif not b or b and e: if b and c or not e and not c: print('mastery') print('finxter')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 14: [1] Create and initialize 5 variables: a, b, c, d, e = False, False, False, False, False.
[2] Check condition (c and not b or a and not d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d or b and not c or a). If it evaluates to True, print finxter to the shell. Otherwise, check condition (d and a). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print learn to the shell.
[5] Check the elif condition (not b or b and e). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (b and c or not e and not c). If it evaluates to True, print mastery to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
mastery
finxter ''' # Puzzle 15
a, b, c, d, e = False, True, False, False, True if not c and c: if a or e and not d: print('mastery') elif e: print('yes') print('finxter')
elif c: if c or d or b and e: print('yes') print('yes')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 15: [1] Create and initialize 5 variables: a, b, c, d, e = False, True, False, False, True.
[2] Check condition (not c and c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a or e and not d). If it evaluates to True, print mastery to the shell. Otherwise, check condition (e). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (c). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (c or d or b and e). If it evaluates to True, print yes to the shell. Otherwise, print yes. ''' # OUTPUT: '''
love ''' # Puzzle 16
a, b, c, d, e = False, False, True, True, True if e or b: if a: print('love') elif not e and not d or b: print('yes') print('code')
elif c or not b: if a or e and c: print('42') print('yes')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 16: [1] Create and initialize 5 variables: a, b, c, d, e = False, False, True, True, True.
[2] Check condition (e or b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a). If it evaluates to True, print love to the shell. Otherwise, check condition (not e and not d or b). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print code to the shell.
[5] Check the elif condition (c or not b). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (a or e and c). If it evaluates to True, print 42 to the shell. Otherwise, print yes. ''' # OUTPUT: '''
code ''' # Puzzle 17
a, b, c, d, e = True, False, False, False, False if d and c and a: if a: print('learn') elif not c: print('python') print('mastery')
elif a or b: if e: print('yes') print('finxter')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 17: [1] Create and initialize 5 variables: a, b, c, d, e = True, False, False, False, False.
[2] Check condition (d and c and a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a). If it evaluates to True, print learn to the shell. Otherwise, check condition (not c). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (a or b). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (e). If it evaluates to True, print yes to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
finxter ''' # Puzzle 18
a, b, c, d, e = True, True, True, False, True if b or a: if not b or not d and a: print('learn') elif not c and c and b: print('42') print('love')
elif c: if e and b: print('learn') print('python')
else: print('code') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 18: [1] Create and initialize 5 variables: a, b, c, d, e = True, True, True, False, True.
[2] Check condition (b or a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not b or not d and a). If it evaluates to True, print learn to the shell. Otherwise, check condition (not c and c and b). If it evaluates to True, print 42 to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (c). If it evaluates to True, move on to the next step [6]. Otherwise, print code to the shell.
[6] Check condition (e and b). If it evaluates to True, print learn to the shell. Otherwise, print python. ''' # OUTPUT: '''
learn
love ''' # Puzzle 19
a, b, c, d, e = True, True, True, True, True if e: if not c or not d: print('mastery') elif d: print('finxter') print('python')
elif d or not d or b: if d: print('yes') print('python')
else: print('learn') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 19: [1] Create and initialize 5 variables: a, b, c, d, e = True, True, True, True, True.
[2] Check condition (e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not c or not d). If it evaluates to True, print mastery to the shell. Otherwise, check condition (d). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (d or not d or b). If it evaluates to True, move on to the next step [6]. Otherwise, print learn to the shell.
[6] Check condition (d). If it evaluates to True, print yes to the shell. Otherwise, print python. ''' # OUTPUT: '''
finxter
python ''' # Puzzle 20
a, b, c, d, e = True, True, True, True, True if not e and not c and d or b: if e and not d and b: print('love') elif e: print('finxter') print('42')
elif not d and b or not e: if b: print('yes') print('finxter')
else: print('finxter') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 20: [1] Create and initialize 5 variables: a, b, c, d, e = True, True, True, True, True.
[2] Check condition (not e and not c and d or b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (e and not d and b). If it evaluates to True, print love to the shell. Otherwise, check condition (e). If it evaluates to True, print finxter to the shell. In any case, move on to the next step [4].
[4] Print 42 to the shell.
[5] Check the elif condition (not d and b or not e). If it evaluates to True, move on to the next step [6]. Otherwise, print finxter to the shell.
[6] Check condition (b). If it evaluates to True, print yes to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
finxter
42 ''' # Puzzle 21
a, b, c, d, e = False, False, False, True, True if b: if d or not c and a: print('love') elif e or a: print('learn') print('love')
elif e and d: if not d: print('code') print('yes')
else: print('42') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 21: [1] Create and initialize 5 variables: a, b, c, d, e = False, False, False, True, True.
[2] Check condition (b). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d or not c and a). If it evaluates to True, print love to the shell. Otherwise, check condition (e or a). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (e and d). If it evaluates to True, move on to the next step [6]. Otherwise, print 42 to the shell.
[6] Check condition (not d). If it evaluates to True, print code to the shell. Otherwise, print yes. ''' # OUTPUT: '''
yes ''' # Puzzle 22
a, b, c, d, e = False, True, True, False, False if e or not e: if b and d and not a or not e: print('yes') elif a and b: print('love') print('mastery')
elif b and not a and d: if e or d and not c: print('love') print('finxter')
else: print('finxter') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 22: [1] Create and initialize 5 variables: a, b, c, d, e = False, True, True, False, False.
[2] Check condition (e or not e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b and d and not a or not e). If it evaluates to True, print yes to the shell. Otherwise, check condition (a and b). If it evaluates to True, print love to the shell. In any case, move on to the next step [4].
[4] Print mastery to the shell.
[5] Check the elif condition (b and not a and d). If it evaluates to True, move on to the next step [6]. Otherwise, print finxter to the shell.
[6] Check condition (e or d and not c). If it evaluates to True, print love to the shell. Otherwise, print finxter. ''' # OUTPUT: '''
yes
mastery ''' # Puzzle 23
a, b, c, d, e = True, True, True, True, False if e or d or a: if d or not d or b or not e: print('learn') elif b and e or a: print('mastery') print('finxter')
elif e: if c and a: print('code') print('code')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 23: [1] Create and initialize 5 variables: a, b, c, d, e = True, True, True, True, False.
[2] Check condition (e or d or a). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d or not d or b or not e). If it evaluates to True, print learn to the shell. Otherwise, check condition (b and e or a). If it evaluates to True, print mastery to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (e). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (c and a). If it evaluates to True, print code to the shell. Otherwise, print code. ''' # OUTPUT: '''
learn
finxter ''' # Puzzle 24
a, b, c, d, e = True, True, True, True, True if a and not e or e: if a and d: print('finxter') elif d or not c and b: print('yes') print('finxter')
elif e: if not a or a: print('learn') print('learn')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 24: [1] Create and initialize 5 variables: a, b, c, d, e = True, True, True, True, True.
[2] Check condition (a and not e or e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (a and d). If it evaluates to True, print finxter to the shell. Otherwise, check condition (d or not c and b). If it evaluates to True, print yes to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (e). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (not a or a). If it evaluates to True, print learn to the shell. Otherwise, print learn. ''' # OUTPUT: '''
finxter
finxter ''' # Puzzle 25
a, b, c, d, e = False, False, False, False, False if not b or c and e: if d or not a or c and a: print('yes') elif c or a: print('python') print('finxter')
elif e: if not e and a or c and d: print('code') print('code')
else: print('mastery') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 25: [1] Create and initialize 5 variables: a, b, c, d, e = False, False, False, False, False.
[2] Check condition (not b or c and e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (d or not a or c and a). If it evaluates to True, print yes to the shell. Otherwise, check condition (c or a). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (e). If it evaluates to True, move on to the next step [6]. Otherwise, print mastery to the shell.
[6] Check condition (not e and a or c and d). If it evaluates to True, print code to the shell. Otherwise, print code. ''' # OUTPUT: '''
yes
finxter ''' # Puzzle 26
a, b, c, d, e = False, True, True, False, False if d and b or e: if b and d and c or a: print('mastery') elif b: print('python') print('love')
elif a and not d: if e and not e: print('mastery') print('42')
else: print('yes') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 26: [1] Create and initialize 5 variables: a, b, c, d, e = False, True, True, False, False.
[2] Check condition (d and b or e). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b and d and c or a). If it evaluates to True, print mastery to the shell. Otherwise, check condition (b). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print love to the shell.
[5] Check the elif condition (a and not d). If it evaluates to True, move on to the next step [6]. Otherwise, print yes to the shell.
[6] Check condition (e and not e). If it evaluates to True, print mastery to the shell. Otherwise, print 42. ''' # OUTPUT: '''
yes ''' # Puzzle 27
a, b, c, d, e = False, True, True, False, False if not d: if c or b and not c: print('finxter') elif b: print('learn') print('finxter')
elif b or c and not d: if not c and a or b: print('code') print('yes')
else: print('love') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 27: [1] Create and initialize 5 variables: a, b, c, d, e = False, True, True, False, False.
[2] Check condition (not d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (c or b and not c). If it evaluates to True, print finxter to the shell. Otherwise, check condition (b). If it evaluates to True, print learn to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (b or c and not d). If it evaluates to True, move on to the next step [6]. Otherwise, print love to the shell.
[6] Check condition (not c and a or b). If it evaluates to True, print code to the shell. Otherwise, print yes. ''' # OUTPUT: '''
finxter
finxter ''' # Puzzle 28
a, b, c, d, e = True, False, True, True, False if b and d or a or c: if b and a or not c or d: print('code') elif not d and a or c: print('python') print('finxter')
elif c or not a and not e: if d and a: print('finxter') print('mastery')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 28: [1] Create and initialize 5 variables: a, b, c, d, e = True, False, True, True, False.
[2] Check condition (b and d or a or c). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (b and a or not c or d). If it evaluates to True, print code to the shell. Otherwise, check condition (not d and a or c). If it evaluates to True, print python to the shell. In any case, move on to the next step [4].
[4] Print finxter to the shell.
[5] Check the elif condition (c or not a and not e). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (d and a). If it evaluates to True, print finxter to the shell. Otherwise, print mastery. ''' # OUTPUT: '''
code
finxter ''' # Puzzle 29
a, b, c, d, e = False, False, False, True, True if e and c and not d: if not d and not c: print('learn') elif d and e: print('code') print('python')
elif b: if d: print('code') print('learn')
else: print('python') ''' SOLUTION HINTS:
Let's go over the relevant parts of puzzle 29: [1] Create and initialize 5 variables: a, b, c, d, e = False, False, False, True, True.
[2] Check condition (e and c and not d). If it evaluates to True, move on the the next step [3]. Otherwise, enter step [5].
[3] Check condition (not d and not c). If it evaluates to True, print learn to the shell. Otherwise, check condition (d and e). If it evaluates to True, print code to the shell. In any case, move on to the next step [4].
[4] Print python to the shell.
[5] Check the elif condition (b). If it evaluates to True, move on to the next step [6]. Otherwise, print python to the shell.
[6] Check condition (d). If it evaluates to True, print code to the shell. Otherwise, print learn. ''' # OUTPUT: '''
python '''

Where to Go From Here?

Congratulations, you made it through all the code puzzles on this site. Did you enjoy to train your rapid code understanding by solving code puzzles? Great, then solve more puzzles for free on Finxter.com!

And share this blog article with a friend to challenge him as well. 🙂

Posted on Leave a comment

How to Get the Key with Minimum Value in a Python Dictionary?

I have spent my morning hours on an important mission. What is the cleanest, fastest, and most concise answer to the following question: How do you find the key with the minimum value in a Python dictionary?  Most answers on the web say you need to use a library but this is not true!

Simply use the min function with the key argument set to dict.get:

income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(min(income, key=income.get))
# Anne

The min function goes over all keys, k, in the dictionary income and takes the one that has minimum value after applying the income.get(k) method. The get() method returns the value specified for key, k, in the dictionary.

Play with it yourself in our interactive code shell:

Now, read the 4-min article or watch the short video to fully understand this concept.

What’s the Min Function in Python?

Most likely, you already know Python’s min(…) function. You can use it to find the minimum value of any iterable or any number of values. Here are a few examples using the min function without specifying any optional arguments.

income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(min(income, key=income.get))
# Anne # Key that starts with 'smallest' letter of the alphabet
print(min(income))
# Anne # Smallest value in the dictionary income
print(min(income.values()))
# 1111 # Smallest value in the given list
print(min([1,4,7,5,3,99,3]))
# 1 # Compare lists element-wise, min is first list to have a larger
# element print(min([1,2,3],[5,6,4]))
# [1, 2, 3] # Smallest value in the given sequence of numbers
print(min(5,7,99,88,123))
# 5

So far so good. The min function is very flexible. It works not only for numbers but also for strings, lists, and any other object you can compare against other objects.

Now, let’s look at the optional arguments of the min function. One of them is 'key'. Let’s find out what it does.

How Does the Key Argument of Python’s min() Function Work?

The last examples show the intuitive workings of the min function: you pass one or more iterables as positional arguments.


Intermezzo: What are iterables? An iterable is an object from which you can get an iterator. An iterator is an object on which you can call the next() method. Each time you call next(), you get the ‘next’ element until you’ve got all the elements from the iterator. For example, Python uses iterators in for loops to go over all elements of a list, all characters of a string, or all keys in a dictionary.


When you specify the key argument, define a function that returns a value for each element of the iterable. Then each element is compared based on the return value of this function, not the iterable element (the default behavior).

Here is an example:

lst = [2, 4, 8, 16] def inverse(val): return -val print(min(lst))
# 2 print(min(lst, key=inverse))
# 16

We define a function inverse() that returns the value multiplied by -1. Now, we print two executions of the min() function.

  • The first is the default execution: the minimum of the list [2, 4, 8, 16] is 2.
  • The second uses key. We specify inverse as the key function. Python applies this function to all values of [2, 4, 8, 16]. It compares these new values with each other and returns the min. Using the inverse function Python does the following mappings:
Original Value  Value after inverse() (basis for min())
2 -2
4 -4
8 -8
16 -16

Python calculates the minimum based on these mappings. In this case, the value 16 (with mapping -16) is the minimum value because -2 > -4 > -8 > -16. 

Now let’s come back to the initial question:

How to Get the Key with the Minimum Value in a Dictionary?

We use the same example as above. The dictionary stores the income of three persons John, Mary, and Alice. Suppose you want to find the person with the smallest income. In other words, what is the key with the minimum value in the dictionary?

Now don’t confuse the dictionary key with the optional key argument of the min() function. They have nothing in common – it’s just an unfortunate coincidence that they have the same name!

From the problem, we know the result is a dictionary key. So, we call min() on the keys of the dictionary. Note that min(income.keys()) is the same as min(income).

To learn more about dictionaries, check out our article Python Dictionary – The Ultimate Guide.

However, we want to compare dictionary values, not keys. We’ll use the key argument of min() to do this. We must pass it a function but which? 

To get the value of 'Anne', we can use bracket notation – income['Anne']. But bracket notation is not a function, so that doesn’t work. Fortunately, income.get('Anne') does (almost) the same as income['Anne'] and it is a function! The only difference is that it returns None if they key is not in the dictionary. So we’ll pass that to the key argument of min().

income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(min(income, key=income.get))
# Anne

How to Get the Key with the Maximum Value in a Dictionary?

If you understood the previous code snippet, this one will be easy. To find the key with maximum value in the dictionary, you use the max() function.

income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(max(income, key=income.get))
# Cara

The only difference is that you use the built-in max() function instead of the built-in min() function. That’s it.

Related article:

Find the Key with the Min Value in a Dictionary – Alternative Methods

There are lots of different ways to solve this problem. They are not as beautiful or clean as the above method. But, for completeness, let’s explore some more ways of achieving the same thing.

In a StackOverflow answer, a user compared nine (!) different methods to find the key with the minimum value in a dictionary. Here they are:

income = {'Anne' : 11111, 'Bert' : 2222, 'Cara' : 9999999} # Convert to lists and use .index(max())
def f1(): v=list(income.values()) k=list(income.keys()) return k[v.index(min(v))] # Dictionary comprehension to swap keys and values
def f2(): d3={v:k for k,v in income.items()} return d3[min(d3)] # Use filter() and a lambda function
def f3(): return list(filter(lambda t: t[1]==min(income.values()), income.items()))[0][0] # Same as f3() but more explicit
def f4(): m=min(income.values()) return list(filter(lambda t: t[1]==m, income.items()))[0][0] # List comprehension
def f5(): return [k for k,v in income.items() if v==min(income.values())][0] # same as f5 but remove the max from the comprehension
def f6(): m=min(income.values()) return [k for k,v in income.items() if v==m][0] # Method used in this article
def f7(): return min(income,key=income.get) # Similar to f1() but shortened to 2 lines
def f8(): v=list(income.values()) return list(income.keys())[v.index(min(v))] # Similar to f7() but use a lambda function
def f9(): return min(income, key=lambda k: income[k]) print(f1())
print(f2())
print(f3())
print(f4())
print(f5())
print(f6())
print(f7())
print(f8())
print(f9())
# Bert (all outputs)

In a benchmark performed on a large dictionary by the StackOverflow user, f1() turned out to be the fastest one.

So the second best way to get the key with the minimum value from a dictionary is:

income = {'Anne' : 11111, 'Bert' : 2222, 'Cara' : 9999999} v=list(income.values())
k=list(income.keys())
print(k[v.index(min(v))])
# Bert

Find Key with Shortest Value in Dictionary

We know how to find the minimum value if the values are numbers. What about if they are lists or strings?

Let’s say we have a dictionary that records the number of days each person worked this month. If they worked a day, we append 1 to that person’s list. If they didn’t work, we don’t do anything.  At the end of the month, our dictionary looks like this.

days_worked = {'Anne': [1, 1, 1, 1], 'Bert': [1, 1, 1, 1, 1, 1], 'Cara': [1, 1, 1, 1, 1, 1, 1, 1]}

The total number of days worked each month is the length of each list. If all elements of two lists are the same (as is the case here), they are compared based on their length.

# Length 2 is less than length 4
>>> [1, 1] < [1, 1, 1, 1]
True

So we can use the same code we’ve been using in the article to find the key with the minimum value.

>>> min(days_worked, key=days_worked.get) 'Anne'

If we update our dictionary so that Bert has worked the most days and apply min() again, Python returns 'Anne'.

>>> days_worked = {'Anne': [1, 1, 1, 1], 'Bert': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'Cara': [1, 1, 1, 1, 1, 1, 1, 1]} # Anne has now worked the least
>>> min(days_worked, key=days_worked.get)

Find Key With Min Value in a List of Dictionaries

Let’s say we have 3 dictionaries containing income information. We want to find the key with the min value from all 3 dictionaries. 

income1 = {'Anne': 1111, 'Bert': 2222, 'Cara': 3333} income2 = {'Dani': 4444, 'Ella': 5555, 'Fred': 6666} income3 = {'Greg': 7777, 'Hope': 8888, 'Igor': 999999999999} list_of_dicts = [income1, income2, income3]

We can see that 'Anne' has the lowest income so we expect that to be returned.

There are several ways to do this. The simplest is to put all key-value pairs into one dictionary using a for loop. Then we call min() as usual.

# Initialise empty dict
>>> big_dict = {} # Use for loop and .update() method to add the key-value pairs
>>> for dic in list_of_dicts: big_dict.update(dic) # Check the result is as expected
>>> big_dict
{'Anne': 1111, 'Bert': 2222, 'Cara': 3333, 'Dani': 4444, 'Ella': 5555, 'Fred': 6666, 'Greg': 7777, 'Hope': 8888, 'Igor': 999999999999} # Call min() and specify key argument
>>> min(big_dict, key=big_dict.get) 'Anne' 

Where to Go From Here?

Every Python master must know the basics. Improving your basic code understanding skills by 20% will improve your productivity by much more than anything else. Why? Because everything else builds upon the basics.

But most material online is tedious and boring. That’s why I’ve written a new and exciting way of learning Python, while measuring and comparing your skills against other coders. Check out the book “Coffee Break Python”. It’s LeanPub 2019 bestseller in the category Python!

Posted on Leave a comment

Python List Length – What’s the Runtime Complexity of len()?

The runtime complexity of the len() function on your Python list is O(1). It takes constant runtime no matter how many elements are in the list. Why? Because the list object maintains an integer counter that increases and decreases as you add and remove list elements. Looking up the value of this counter takes constant time.

Python list objects keep track of their own length. When you call the function len(...) on a list object, here’s what happens (roughly):

  • The Python virtual machine looks up the len(...) function in a dictionary to find the associated implementation.
  • You pass a list object as an argument to the len() function so the Python virtual machine checks the __len__ method of the list object.
  • The method is implemented in C++ and it’s just a counter that’s increased each time you add an element to the list and decreased if you remove an element from the list. For example, say, the variable length stores the current length of the list. The method then returns the value self.length.
  • Done.

Here’s a snippet of the C++ implementation of the list data structure:

static int
list_resize(PyListObject *self, Py_ssize_t newsize)
{ PyObject **items; size_t new_allocated, num_allocated_bytes; Py_ssize_t allocated = self->allocated; // some implementation details Py_SET_SIZE(self, newsize); self->allocated = new_allocated; return 0;
}

What’s the Runtime Complexity of Other Python List Methods?

Here’s the table based on the official Python wiki:

Operation Average Case Amortized Worst Case
copy() O(n) O(n)
append() O(1) O(1)
pop() O(1) O(1)
pop(i) O(k) O(k)
insert() O(n) O(n)
list[i] O(1) O(1)
list[i] = x O(1) O(1)
remove(x) O(n) O(n)
for i in list O(n) O(n)
list[i:j] O(k) O(k)
del list[i:j] O(n) O(n)
list[i:j] = y O(k+n) O(k+n)
extend() O(k) O(k)
sort() O(n log n) O(n log n)
[…] * 10 O(nk) O(nk)
x in lst O(n)
min(lst), max(lst) O(n)
len(lst) O(1) O(1)

The Python list is implemented using a C++ array. This means that it’s generally slow to modify elements at the beginning of each list because all elements have to be shifted to the right. If you add an element to the end of a list, it’s usually fast. However, resizing an array can become slow from time to time if more memory has to be allocated for the array.

Where to Go From Here

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.

Posted on Leave a comment

How to Create Your Own Search Engine in a Single Line of Python?

This Python One-Liner is part of my Python One-Liners book with NoStarch Press.

Here’s the code from the video:

letters_amazon = '''
We spent several years building our own database engine,
Amazon Aurora, a fully-managed MySQL and PostgreSQL-compatible
service with the same or better durability and availability as
the commercial engines, but at one-tenth of the cost. We were
not surprised when this worked. ''' find = lambda x, q: x[x.find(q)-18:x.find(q)+18] if q in x else -1 print(find(letters_amazon, 'SQL'))

Try It Yourself:

Related Articles: