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:

Posted on Leave a comment

Python – How to Sort a List of Dictionaries?

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 sort a list of dictionaries in all possible variations. [1] So let’s get started!

How to Sort a List of Dictionaries …

… By Value?

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:

You’ll learn about the second way below (where you use the itemgetter function from the operator module).

Related articles on the Finxter blog:

… Using Itemgetter?

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

Minimal Example: Consider again 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: Again, you’re going to define a key function. But instead of creating it yourself with the lambda keyword, you’re going to use an existing one. In particular, you’ll use the itemgetter function from the operator module 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:

# Import the itemgetter function from the operator module
from operator import itemgetter # 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=itemgetter('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}]

Now, you know how to sort a list of dictionaries by value. But what if you want to sort by key?

… By Key?

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

Solution: It doesn’t make sense. If you assume that all dictionaries have that same particular key, you cannot really sort because all dictionaries have the same key. If there’s no tie-breaker, it’s impossible to do. But even if there’s a tie-breaker (e.g. the value associated to the key), it doesn’t make sense because you could have sorted by value in the first place.

… By Multiple Keys?

Problem: Given a list of dictionaries. How do you sort by multiple key value pairs?

Minimal Example: Consider the following example where you want to sort a list of database entries (e.g. each stored as a dictionary) by value of the key 'username'. If the 'username' is the same, you use the 'joined' value as a tiebreaker. If the 'joined' date is the same, you use the 'age' as a tie breaker.

db = [{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Bob', 'joined': 2018, 'age': 19}, {'username': 'Alice', 'joined': 2020, 'age': 31}] 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:

[{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Alice', 'joined': 2020, 'age': 31}, {'username': 'Bob', 'joined': 2018, 'age': 19}]

Solution: You’re going to define a key function with the lambda keyword. But instead of returning a single value to a given key, you return a tuple—one entry per value that should be considered. For example, the database entry {'username': 'Alice', 'joined': 2020, 'age': 23} is mapped to ('Alice', 2020, 23). This ensures that two tuples that have the same first tuple value will still be sorted correctly by using the second tuple value as a tiebreaker.

Here’s the code:

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Bob', 'joined': 2018, 'age': 19}, {'username': 'Alice', 'joined': 2020, 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the tuple of values.
db_sorted = sorted(db, key=lambda row: (row['username'], row['joined'], row['age'])) # Print everything to the shell
print(db_sorted)

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.

[{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Alice', 'joined': 2020, 'age': 31}, {'username': 'Bob', 'joined': 2018, 'age': 19}]

In this example, the dictionary value for the key ‘joined’ was an integer number. But what if it’s a date?

… By Date?

Problem: Given a list of dictionaries. How do you sort the list of dictionaries by date?

Minimal Example: Consider the following example where you want to sort a list of database entries (e.g. each stored as a dictionary) by value of the key 'joined' that is from type date or timedate.

db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] db_sorted = # ... sorting magic here ... print(db_sorted)

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

[{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}]

Solution: Define a key function with the lambda keyword. Simply return the string value for the key 'joined' for a given dictionary. This return value is then used to sort the dictionaries in the list.

As the join dates are given as strings in the form year-month-day (e.g. '2020-08-08'), the default alphabetical sort will also lead to a sorted overall list of dictionaries: the dictionary row with the earliest join date will be the first in the resulting list.

Here’s the code:

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the join date.
db_sorted = sorted(db, key=lambda row: row['joined']) # Print everything to the shell
print(db_sorted)

The output is the sorted dictionary. Note that the first dictionary has the earliest and the third dictionary has the latest join date.

[{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}]

You can use a similar method if the dictionary values are of format datetime as they are also comparable with default comparison operators >, <, >=, <=, and ==. [2]

… In Descending Order?

Problem: The default ordering of any Python list sort routine (sorted() and list.sort()) is in ascending order. This also holds if you sort a list of dictionaries. How can you sort in descending order?

Solution: If you want to sort in descending order, you can do one of the following:

  • Use slicing to reverse the sorted list.
  • Use the reverse=True argument of the sorted() or list.sort() methods.

Both ways are equivalent. Have a look at the previous example first using the reverse argument:

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the join date.
db_sorted = sorted(db, key=lambda row: row['joined'], reverse=True) # Print everything to the shell
print(db_sorted)

Output:

[{'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Alice', 'joined': '2019-03-02', 'age': 23}]

And second using slicing with negative step size (without the reverse argument):

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the join date.
db_sorted = sorted(db, key=lambda row: row['joined'])[::-1] # Print everything to the shell
print(db_sorted)

Same output:

[{'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Alice', 'joined': '2019-03-02', 'age': 23}]

… in Ascending Order?

The default ordering of any Python list sort routine (sorted() and list.sort()) is in ascending order. This also holds if you sort a list of dictionaries.

Where to Go From Here

In this article, you’ve learned how to sort a list of dictionaries. In summary, use the sorted() method with a key function as argument. This gives you the flexibility to customize how exactly you want to sort the dictionary—just map each dictionary to a comparable value.

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

Matplotlib 3D Plot – A Helpful Illustrated Guide

Are you tired with the same old 2D plots? Do you want to take your plots to the next level? Well look no further, it’s time to learn how to make 3D plots in matplotlib.

In addition to import matplotlib.pyplot as plt and calling plt.show(), to create a 3D plot in matplotlib, you need to:

  1. Import the Axes3D object
  2. Initialize your Figure and Axes3D objects
  3. Get some 3D data
  4. Plot it using Axes notation and standard function calls
# Standard import
import matplotlib.pyplot as plt # Import 3D Axes from mpl_toolkits.mplot3d import axes3d # Set up Figure and 3D Axes fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Get some 3D data
X = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Y = [2, 5, 8, 2, 10, 1, 10, 5, 7, 8]
Z = [6, 3, 9, 6, 3, 2, 3, 10, 2, 4] # Plot using Axes notation and standard function calls
ax.plot(X, Y, Z)
plt.show()

Awesome! You’ve just created your first 3D plot! Don’t worry if that was a bit fast, let’s dive into a more detailed example.

Try it yourself with our interactive Python shell. Just execute the code and look at the generated “plot.png” file:

Related article:

Matplotlib 3D Plot Example

If you are used to plotting with Figure and Axes notation, making 3D plots in matplotlib is almost identical to creating 2D ones. If you are not comfortable with Figure and Axes plotting notation, check out this article to help you.

Besides the standard import matplotlib.pyplot as plt, you must alsofrom mpl_toolkits.mplot3d import axes3d. This imports a 3D Axes object on which a) you can plot 3D data and b) you will make all your plot calls with respect to.

You set up your Figure in the standard way

fig = plt.figure()

And add a subplots to that figure using the standard fig.add_subplot() method. If you just want a single Axes, pass 111 to indicate it’s 1 row, 1 column and you are selecting the 1st one. Then you need to pass projection='3d' which tells matplotlib it is a 3D plot.

From now on everything is (almost) the same as 2D plotting. All the functions you know and love such as ax.plot() and ax.scatter() accept the same keyword arguments but they now also accept three positional arguments – X,Y and Z.

In some ways 3D plots are more natural for us to work with since we live in a 3D world. On the other hand, they are more complicated since we are so used to 2D plots. One amazing feature of Jupyter Notebooks is the magic command %matplotlib notebook which, if ran at the top of your notebook, draws all your plots in an interactive window. You can change the orientation by clicking and dragging (right click and drag to zoom in) which can really help to understand your data.

As this is a static blog post, all of my plots will be static but I encourage you to play around in your own Jupyter or IPython environment.

Related article:

Matplotlib 3D Plot Line Plot

Here’s an example of the power of 3D line plots utilizing all the info above.

# Standard imports
import matplotlib.pyplot as plt
import numpy as np # Import 3D Axes from mpl_toolkits.mplot3d import axes3d # Set up Figure and 3D Axes fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Create space of numbers for cos and sin to be applied to
theta = np.linspace(-12, 12, 200)
x = np.sin(theta)
y = np.cos(theta) # Create z space the same size as theta z = np.linspace(-2, 2, 200) ax.plot(x, y, z)
plt.show()

To avoid repetition, I won’t explain the points I have already made above about imports and setting up the Figure and Axes objects.

I created the variable theta using np.linspace which returns an array of 200 numbers between -12 and 12 that are equally spaced out i.e. there is a linear distance between them all. I passed this to np.sin() and np.cos() and saved them in variables x and y.

If you just plotted x and y now, you would get a circle. To get some up/down movement, you need to modify the z-axis. So, I used np.linspace again to create a list of 200 numbers equally spaced out between -2 and 2 which can be seen by looking at the z-axis (the vertical one).

Note: if you choose a smaller number of values for np.linspace the plot is not as smooth.

For this plot, I set the third argument of np.linspace to 25 instead of 200. Clearly, this plot is much less smooth than the original and hopefully gives you an understanding of what is happening under the hood with these plots. 3D plots can seem daunting at first so my best advice is to go through the code line by line.

Matplotlib 3D Plot Scatter

Creating a scatter plot is exactly the same as making a line plot but you call ax.scatter instead.

Here’s a cool plot that I adapted from this video. If you sample a normal distribution and create a 3D plot from it, you get a ball of points with the majority focused around the center and less and less the further from the center you go.

import random
random.seed(1) # Create 3 samples from normal distribution with mean and standard deviation of 1
x = [random.normalvariate(1, 1) for _ in range(400)]
y = [random.normalvariate(1, 1) for _ in range(400)]
z = [random.normalvariate(1, 1) for _ in range(400)] # Set up Figure and Axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Plot
ax.scatter(x, y, z)
plt.show()

First, I imported the python random module and set the seed so that you can reproduce my results. Next, I used three list comprehensions to create 3 x 400 samples of a normal distribution using the random.normalvariate() function. Then I set up the Figure and Axes as normal and made my plot by calling ax.scatter().

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z)
plt.show()

In this example, I plotted the same X, Y and Z lists as in the very first example. I want to highlight to you that some of the points are darker and some are more transparent – this indicates depth. The ones that are darker in color are in the foreground and those further back are more see-through.

If you plot this in IPython or an interactive Jupyter Notebook window and you rotate the plot, you will see that the transparency of each point changes as you rotate.

Matplotlib 3D Plot Rotate

The easiest way to rotate 3D plots is to have them appear in an interactive window by using the Jupyter magic command %matplotlib notebook or using IPython (which always displays plots in interactive windows). This lets you manually rotate them by clicking and dragging. If you right-click and move the mouse, you will zoom in and out of the plot. To save a static version of the plot, click the save icon.

It is possible to rotate plots and even create animations via code but that is out of the scope of this article.

Matplotlib 3D Plot Axis Labels

Setting axis labels for 3D plots is identical for 2D plots except now there is a third axis – the z-axis – you can label.

You have 2 options:

  1. Use the ax.set_xlabel(), ax.set_ylabel() and ax.set_zlabel() methods, or
  2. Use the ax.set() method and pass it the keyword arguments xlabel, ylabel and zlabel.

Here is an example using the first method.

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z) # Method 1
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis') plt.show()

Now each axis is labeled as expected.

You may notice that the axis labels are not particularly visible using the default settings. You can solve this by manually increasing the size of the Figure with the figsize argument in your plt.figure() call.

One thing I don’t like about method 1 is that it takes up 3 lines of code and they are boring to type. So, I much prefer method 2.

# Set Figure to be 8 inches wide and 6 inches tall
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z) # Method 2 - set all labels in one line of code!
ax.set(xlabel='X axis', ylabel='Y axis', zlabel='Z axis') plt.show()

Much better! Firstly, because you increased the size of the Figure, all the axis labels are clearly visible. Plus, it only took you one line of code to label them all. In general, if you ever use a ax.set_<something>() method in matplotlib, it can be written as ax.set(<something>=) instead. This saves you space and is nicer to type, especially if you want to make numerous modifications to the graph such as also adding a title.

Matplotlib 3D Plot Legend

You add legends to 3D plots in the exact same way you add legends to any other plots. Use the label keyword argument and then call ax.legend() at the end.

import random random.seed(1)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Plot and label original data
ax.scatter(X, Y, Z, label='First Plot') # Randomly re-order the data
for data in [X, Y, Z]: random.shuffle(data) # Plot and label re-ordered data
ax.scatter(X, Y, Z, label='Second Plot') ax.legend(loc='upper left')
plt.show()

In this example, I first set the random seed to 1 so that you can reproduce the same results as me. I set up the Figure and Axes as expected, made my first 3D plot using X, Y and Z and labeled it with the label keyword argument and an appropriate string.

To save me from manually creating a brand new dataset, I thought it would be a good idea to make use of the data I already had. So, I applied the random.shuffle() function to each of X, Y and Z which mixes the values of the lists in place. So, calling ax.plot() the second time, plotted the same numbers but in a different order, thus producing a different looking plot. Finally, I labeled the second plot and called ax.legend(loc='upper left') to display a legend in the upper left corner of the plot.

All the usual things you can do with legends are still possible for 3D plots. If you want to learn more than these basic steps, check out my comprehensive guide to legends in matplotlib.

Note: If you run the above code again, you will get a different looking plot. This is because you will start with the shuffled X, Y and Z lists rather than the originals you created further up inb the post.

Matplotlib 3D Plot Background Color

There are two backgrounds you can modify in matplotlib – the Figure and the Axes background. Both can be set using either the .set_facecolor('color') or the .set(facecolor='color') methods. Hopefully, you know by now that I much prefer the second method over the first!

Here’s an example where I set the Figure background color to green and the Axes background color to red.

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.plot(X, Y, Z) # Axes color is red
ax.set(facecolor='r')
# Figure color is green
fig.set(facecolor='g')
plt.show()

The first three lines are the same as a simple line plot. Then I called ax.set(facecolor='r') to set the Axes color to red and fig.set(facecolor='g') to set the Figure color to green.

In an example with one Axes, it looks a bit odd to set the Figure and Axes colors separately. If you have more than one Axes object, it looks much better.

# Set up Figure and Axes in one function call
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 6), subplot_kw=dict(projection='3d')) colors = ['r', 'g', 'y', 'b'] # iterate over colors and all Axes objects
for c, ax in zip(colors, axes.flat): ax.plot(X, Y, Z) # Set Axes color ax.set(facecolor=c) # Set Figure color
fig.set(facecolor='pink')
plt.show()

In this example, I used plt.subplots() to set up an 8×6 inch Figure containing four 3D Axes objects in a 2×2 grid. The subplot_kw argument accepts a dictionary of values and these are passed to add_subplot to make each Axes object. For more info on using plt.subplots() check out my article.

Then I created the list colors containing 4 matplotlib color strings. After that, I used a for loop to iterate over colors and axes.flat. In order to iterate over colors and axes together, they need to be the same shape. There are several ways to do this but using the .flat attribute works well in this case.

Finally, I made the same plot on each Axes and set the facecolors. It is clear now why setting a Figure color can be more useful if you create subplots – there is more space for the color to shine through.

Conclusion

That’s it, you now know the basics of creating 3D plots in matplotlib!

You’ve learned the necessary imports you need and also how to set up your Figure and Axes objects to be 3D. You’ve looked at examples of line and scatter plots. Plus, you can modify these by rotating them, adding axis labels, adding legends and changing the background color.

There is still more to be learned about 3D plots such as surface plots, wireframe plots, animating them and changing the aspect ratio but I’ll leave those for another article.

Where To Go From Here?

Do you wish you could be a programmer full-time but don’t know how to start?

Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back!

https://tinyurl.com/become-a-python-freelancer

It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.

These are proven, no-BS methods that get you results fast.

This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed.

https://tinyurl.com/become-a-python-freelancer