Coffee Break Python Workbook Mayer
Coffee Break Python Workbook Mayer
Workbook
i
Contents
Contents ii
1 Introduction 1
ii
CONTENTS iii
3 Elo 19
3.1 How to Use This Book . . . . . . . . . . 19
3.2 How to Test and Train Your Skills? . . . 21
3.3 What Can This Book Do For You? . . . 25
6.1 Maximum . . . . . . . . . . . . . . . . . 63
6.2 Memory addresses . . . . . . . . . . . . . 64
6.3 Swapping Values . . . . . . . . . . . . . 65
6.4 The Boolean Operator AND . . . . . . . 67
6.5 The Boolean Operator OR . . . . . . . . 69
6.6 Boolean Operators . . . . . . . . . . . . 71
6.7 Arithmetic Expressions . . . . . . . . . . 73
6.8 Integer Division and Modulo . . . . . . . 75
6.9 Building Strings . . . . . . . . . . . . . . 77
6.10 The len() Function . . . . . . . . . . . 78
6.11 String Indices . . . . . . . . . . . . . . . 79
6.12 The upper() Function . . . . . . . . . . . 80
6.13 The lower() Function . . . . . . . . . . . 81
6.14 Somebody Is Shouting . . . . . . . . . . 82
6.15 Counting Characters . . . . . . . . . . . 83
6.16 String Lengths . . . . . . . . . . . . . . 84
6.17 Finding Characters in Strings . . . . . . 85
6.18 Not Finding Characters in Strings . . . . 86
6.19 Counting Letters . . . . . . . . . . . . . 87
6.20 Min() and Max() of a String . . . . . . . 88
6.21 Reversed Strings . . . . . . . . . . . . . 89
6.22 String Equality . . . . . . . . . . . . . . 90
6.23 Slicing I . . . . . . . . . . . . . . . . . . 92
6.24 Slicing II . . . . . . . . . . . . . . . . . . 93
6.25 Slicing III . . . . . . . . . . . . . . . . . 94
6.26 Slicing IV . . . . . . . . . . . . . . . . . 95
6.27 Slicing V . . . . . . . . . . . . . . . . . . 96
CONTENTS v
Introduction
1
2 CHAPTER 1. INTRODUCTION
4
2.1. OVERCOME THE KNOWLEDGE GAP 5
2
http://journals.sagepub.com/doi/abs/10.1177/
1529100612453266
2.9. MAKE CODE A FIRST-CLASS CITIZEN 15
self staring at the code for a long time until the insight
strikes. This creates new synapses in your brain that
help you understand, write, and read code fast. Placing
code in the center of the learning process means you will
develop an intuition as powerful as the experts. Maxi-
mize the learning time you spend looking at code rather
than other things.
19
20 CHAPTER 3. ELO
2000
Your Elo
1500
1000
500
0
0 20 40 60 80 100 120
Number of Solved Puzzles
a tree and I will spend the first four sharpening the ax.”
Do not fool yourself into the belief that just doing it
is the most effective road to reach any goal. You must
constantly sharpen the saw to be successful in any disci-
pline. Learning to code is best done via practical coding
and investing time into your personal growth. Millions
of computer scientists have an academic background.
They know that solving hundreds or thousands of toy
examples in their studies built a strong foundation.
How am I supposed to solve this puzzle if I do not know
the meaning of this specific Python language feature?
Guess it! Python is an intuitive language. Think about
potential meanings. Solve the puzzle for each of them—
a good exercise for your brain. The more you work on
the puzzle, even with imperfect knowledge, the better
you prepare your brain to absorb the puzzle’s explana-
tion.
How does this book interplay with the puzzles at Finxter.
com ? My goal is to remove barriers to learning Python.
Thus, many puzzles are available for free online. This
book is based on some puzzles available at Finxter, but
it extends them with more detailed and structured in-
formation. Nevertheless, if you don’t like reading books,
feel free to check out the website.
Anyway, why do some people thrive in their fields and
become valued experts while others stagnate? They
28 CHAPTER 3. ELO
29
CHAPTER 4. A QUICK OVERVIEW OF THE
30 PYTHON LANGUAGE
You can download all five cheat sheets as concise PDFs.
Post them to your wall until you know them by heart:
https://blog.finxter.com/subscribe/.
4.1 Keywords
All programming languages reserve certain words to have
a special meaning. These words are called keywords.
With keywords, you can issue commands to the com-
piler or interpreter. They let you tell the computer what
to do. Without keywords, the computer would not be
able to understand the seemingly random text in your
code file. Note that, as keywords are reserved words,
you cannot use them as variable names.
The most important Python keywords are:
4.4 Classes
Object-oriented programming (OOP) is an influential,
powerful, and expressive programming paradigm. The
programmer thinks in terms of classes and objects. A
class is a blueprint for an object. An object contains
specific data and provides the functionality specified in
the class.
Say, you are programming a game to build, simulate,
and grow cities. In object-oriented programming, you
would represent all things (buildings, persons, or cars)
as objects. For example, each building object stores
data such as name, size, and price tag. Additionally,
each building provides a defined functionality such as
calculate_monthly_earnings(). This simplifies the
reading and understanding of your code for other pro-
grammers. Even more important, you can now easily
divide responsibilities between programmers. For ex-
ample, you code the buildings and your colleague codes
the moving cars.
In short, object-oriented programming helps you to write
readable code. By learning it, your ability to collabo-
rate with others on complex problems improves. The
next cheat sheet introduces the most basic concepts.
CHAPTER 4. A QUICK OVERVIEW OF THE
42 PYTHON LANGUAGE
4.4. CLASSES 43
CHAPTER 4. A QUICK OVERVIEW OF THE
44 PYTHON LANGUAGE
4.5 Functions and Tricks
Python is full of extra tricks and special functionality.
Learning these tricks makes you more efficient and pro-
ductive. But more importantly, these tricks make pro-
gramming easy and fun. In the next cheat sheet, I show
you the most important ones.
4.5. FUNCTIONS AND TRICKS 45
ADVANCED FUNCTIONS
map(func, iter)
Executes the function on all elements of the iterable. Example:
list(map(lambda x: x[0], ['red', 'green', 'blue']))
# Result: ['r', 'g', 'b']
map(func, i1, ..., ik)
Executes the function on all k elements of the k iterables. Example:
list(map(lambda x, y: str(x) + ' ' + y + 's' , [0, 2, 2],
['apple', 'orange', 'banana']))
# Result: ['0 apples', '2 oranges', '2 bananas']
string.join(iter)
Concatenates iterable elements separated by string. Example:
' marries '.join(list(['Alice', 'Bob']))
# Result: 'Alice marries Bob'
filter(func, iterable)
Filters out elements in iterable for which function returns False (or 0). Example:
list(filter(lambda x: True if x>17 else False, [1, 15, 17,
18])) # Result: [18]
string.strip()
Removes leading and trailing whitespaces of string. Example:
print(" \n \t 42 \t ".strip()) # Result: 42
sorted(iter)
Sorts iterable in ascending order. Example:
sorted([8, 3, 2, 42, 5]) # Result: [2, 3, 5, 8, 42]
sorted(iter, key=key)
Sorts according to the key function in ascending order. Example:
sorted([8, 3, 2, 42, 5], key=lambda x: 0 if x==42 else x)
# [42, 2, 3, 5, 8]
help(func)
Returns documentation of func. Example:
CHAPTER 4. A QUICK OVERVIEW OF THE
46 PYTHON LANGUAGE
help(str.upper()) # Result: '... to uppercase.'
zip(i1, i2, ...)
Groups the i-th elements of iterators i1, i2, … together. Example:
list(zip(['Alice', 'Anna'], ['Bob', 'Jon', 'Frank']))
# Result: [('Alice', 'Bob'), ('Anna', 'Jon')]
Unzip
Equal to: 1) unpack the zipped list, 2) zip the result. Example:
list(zip(*[('Alice', 'Bob'), ('Anna', 'Jon')]
# Result: [('Alice', 'Anna'), ('Bob', 'Jon')]
enumerate(iter)
Assigns a counter value to each element of the iterable. Example:
list(enumerate(['Alice', 'Bob', 'Jon']))
# Result: [(0, 'Alice'), (1, 'Bob'), (2, 'Jon')]
TRICKS
python -m http.server <P>
Want to share files between your PC and your phone? Run this command in
your PC’s shell. <P> is any port number between 0–65535. Type < IP address
of PC>:<P> in the phone’s browser. Now, you can browse the files in the PC’s
directory.
Read comic
import antigravity
Opens the comic series xkcd in your web browser
Zen of Python
import this
'...Beautiful is better than ugly. Explicit is ...'
Swapping variables
This is a breeze in Python. No offense, Java! Example:
a, b = 'Jane', 'Alice'
a, b = b, a
# Result: a = 'Alice', b = 'Jane'
4.5. FUNCTIONS AND TRICKS 47
Unpacking arguments
Use a sequence as function arguments via asterisk operator *. Use a dictionary
(key, value) via double asterisk operator **. Example:
def f(x, y, z):
return x + y * z
f(*[1, 3, 4]) # 13
f(**{'z' : 4, 'x' : 1, 'y' : 3}) # 13
Extended Unpacking
Use unpacking for multiple assignment feature in Python. Example:
a, *b = [1, 2, 3, 4, 5]
# Result: a = 1, b = [2, 3, 4, 5]
Merge two dictionaries
Use unpacking to merge two dictionaries into a single one. Example:
x={'Alice' : 18}
y={'Bob' : 27, 'Ann' : 22}
z = {**x,**y}
# Result: z = {'Alice': 18, 'Bob': 27, 'Ann': 22}
5
a = 20
print(a)
48
5.1. PRINTING VALUES 49
a = 20
b = 11
c = a - b
print(c)
my_string = 'abc'
print(my_string)
a = 2
print(type(a))
x = True
print(type(x))
5.6 Minimum
# Elo 1245
print(min([1, 2, 3, -4]))
first_str = 'Hello'
second_str = " world!"
print(str_)
my_str = '''Hello
world
how are
you?'''
print(my_str)
This puzzle does the same as the puzzle before but with
one difference: instead of encoding the new line using
'\n', we define a multi-line string using triple quote
notation.
The result is (again):
Hello
world
how
are you?
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
bool_var = 1 == 1
print(bool_var)
bool_var = 1 > 2
print(bool_var)
a = b = c = 1
print(b)
6.1 Maximum
# Elo 1401
63
CHAPTER 6. PUZZLES: SCHOLAR TO
64 INTERMEDIATE
In this puzzle, we pass a list of arithmetic expressions
to the max() function. After evaluating these expres-
sions, the max() function returns the greatest value from
the list. In our case, the list looks like: [5, 10, 4.0].
Hence, this code prints 10.
question = answer
print(id(question)==id(answer))
a = 5
b = 'my string'
tmp = a
a = b
b = tmp
print(a)
print(b)
CHAPTER 6. PUZZLES: SCHOLAR TO
66 INTERMEDIATE
What’s the output of this code snippet?
Correct: +10 Elo points / Wrong: -10 Elo points
6.4. THE BOOLEAN OPERATOR AND 67
and_result = t1 and t2
print(and_result)
and_result = t1 and f1
print(and_result)
and_result = f1 and f2
print(and_result)
and_result = f1 and t2
print(and_result)
Here, we have four variables t1, t2, f1, f2. The vari-
ables t* are True and the variables f* are False.
The puzzle performs the Boolean and operation on all
combinations of these four variables.
The and operation is True if and only if both operands
are True. Hence, the result is:
True
False
False
False
t1 = True
t2 = True
f1 = False
f2 = False
or_result = t1 or t2
print(or_result)
or_result = t1 or f1
print(or_result)
CHAPTER 6. PUZZLES: SCHOLAR TO
70 INTERMEDIATE
or_result = f2 or t2
print(or_result)
or_result = f1 or f2
print(or_result)
t1 = 5 + 2 == 7
f1 = 2 - 1 > 3
r = t1 or False
r = r and True and f1
print(r)
r = 3 + 5 - 2
print(type(r))
days_count = 219
days_per_week = 7
ha = 'ha'
ho = 'ho'
print(laughter)
my_str = 'cat'
length = len(my_str)
print(length)
my_str = 'superman'
print(my_str[0])
print(my_str[1])
print(my_str[len(my_str) - 1])
s u p e r m a n
0 1 2 3 4 5 6 7
print(shout)
print(whisper)
print(text)
print(space_count == total_count)
print(space_count == total_count)
print(idx)
print(idx > 0)
my_str = 'python'
print(min(my_str) + max(my_str))
my_str = 'python'
print(my_str[::-1])
my_str = 'python'
6.22. STRING EQUALITY 91
print(are_equal)
6.23 Slicing I
# Elo 1431
my_str = 'python'
my_substring = my_str[4:]
print(my_substring)
6.24 Slicing II
# Elo 1598
my_str = 'python'
my_substr = my_str[::2]
print(my_substr)
my_str = 'AaBbCcDdEeFf'
big = my_str[::2]
small = my_str[1::2]
6.26 Slicing IV
# Elo 1588
chars_1 = 'Rzotbo'
chars_2 = 'tigno'
print(mystery)
6.27 Slicing V
# Elo 1395
my_str = 'Batman'
other_str = my_str[0:len(my_str)]
print(other_str)
my_str = 'Aquaman'
id_1 = id(my_str)
my_str = my_str[4:]
id_2 = id(my_str)
print(id_1 == id_2)
my_list = [
'apple',
'banana',
'orange',
]
item = my_list[len(my_list)-2]
print(item)
6.29. ACCESSING LIST ITEMS I 99
my_list = [
'apple',
'orange',
'banana',
]
item = my_list[1]
print(item)
my_list = [
'apple',
'banana',
'orange',
]
item = my_list.pop()
print(item)
phone = 'smartphone'
x = phone.startswith('smart')
y = phone.endswith('phone')
print(x and y)
phone = 'smartphone'
x = 'xyz' in phone
print(not x)
print(x)
print(str_1 == str_2)
shopping_list = [
'bread',
'milk',
'cheese',
]
string = ','.join(shopping_list)
print(string)
my_list = [
'Bob',
'Alice',
'Donald',
'Goofy',
]
your_list = my_list.copy()
print(id(your_list) == id(my_list))
my_list = []
my_list.append('Tomato')
my_list = my_list + ['Pizza']
print(my_list)
odd = [1, 3, 5, 7]
even = [0, 2, 4, 6]
odd.extend(even)
print(len(odd))
my_list = []
my_list.append(1)
my_list.append(2)
my_list.pop()
print(len(my_list))
my_list = [4, 5, 6]
index = 0
my_list.insert(index, 3)
print(my_list[1])
my_list = [1, 2, 3, 4]
value = 2
index = 2
my_list.remove(value)
print(my_list[index])
my_list = [1, 2, 3, 3, 2, 3]
index = my_list.index(3)
print(index)
my_list = [1, 2, 3, 0, 2, 3]
count = my_list.count(3)
print(count)
print(len(my_list))
my_list = [4, 7, 3, 9, 1]
my_list.sort()
print(my_list)
my_list = [10, 9, 8, 7]
my_list.reverse()
print(my_list)
print(x)
bool_val = all([
1 == 1,
7 // 2 == 2 + 1,
2 == 6 % 4,
])
print(bool_val)
len_of_list = len(list(range(10)))
print(len_of_list)
l = list(range(10, 1, -1))
print(l)
a = 'world!'
b = 'hello '
b, a = a, b
print(a + b)
my_list = [1, 1, 1, 1]
my_list[1::2] = [2, 3]
print(my_list)
word = 'radar'
p = word == word[::-1]
print(p)
value_0 = int(True)
value_1 = int(False)
string = str(value_0) + str(value_1)
print(string)
print(1000 * False)
print((3 == 4) == 0)
print(bool([]))
• empty sequences,
• 0,
• 0.0,
n = 0
6.61. LOOPING OVER RANGES 133
print(n)
str_ = ''
for c in reversed('nohtyp'):
str_ += c
print(str_)
s = sum([
True,
False,
True,
True,
])
print(s)
my_list = []
id_1 = id(my_list)
print(id_1 == id_2)
my_list = []
id_1 = id(my_list)
my_list.append(1)
id_2 = id(my_list)
print(id_1 == id_2)
b = all([
bool('0'),
bool('?'),
bool('-'),
bool('e'),
])
print(b)
a = complex(2, 4)
b = complex(1, -3)
print(a + b)
6.68 Tuples
# Elo 1462
print(type(x) == type(y))
1. t1 = (1, 2), or
2. t2 = 1, 2.
x, y, z = 'cat'
print(y)
So printing y returns a.
my_bools = []
result = all(my_bools)
print(result)
b = any([
bool(None),
bool(0),
bool(dict()),
])
CHAPTER 6. PUZZLES: SCHOLAR TO
144 INTERMEDIATE
print(b)
1. it exists, and
2. len(c) > 0
my_list = [1, 1, 0]
s = 3
if my_list:
s = sum(my_list)
CHAPTER 6. PUZZLES: SCHOLAR TO
146 INTERMEDIATE
print(s)
a = complex(2, 5)
b = complex(a.imag, a.real)
print(b)
CHAPTER 6. PUZZLES: SCHOLAR TO
148 INTERMEDIATE
What’s the output of this code snippet?
Correct: +10 Elo points / Wrong: -10 Elo points
6.74. TUPLE CONFUSION 149
p1 = (1, -1)
p2 = (2, 5)
p3 = (p1[0] + p2[0], p1[1] + p2[1])
print(p3)
index = 5
s = 'g'
print(s)
6.75. UNDERSTANDING WHILE ... ELSE (1/3) 151
index = 5
string = 'g'
6.76. UNDERSTANDING WHILE ... ELSE (2/3) 153
print(string)
index = 5
string = 'g'
else:
string += 'd'
6.77. UNDERSTANDING WHILE ... ELSE (3/3) 155
print(string)
print(magic(2, 3))
6.79 Dictionary
# Elo 1531
dict_ = {
1: 'one',
2: 'two',
3: 'three',
}
def to_str(number):
if number in dict_:
return dict_[number]
else:
return '?'
s1 = to_str(2)
s2 = to_str(7)
print(s1 + s2)
6.79. DICTIONARY 159
sales = {
100: {'item': 'apple', 'price': .95},
101: {'item': 'banana', 'price': .55},
102: {'item': 'orange', 'price': .75},
}
6.80. DICTIONARY OF DICTIONARIES 161
value = sales[102].get('price')
print(value)
roman = {
1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V',
6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX', 10: 'X'
6.81. REVERSE DICTIONARY INDEX 163
arab = {}
print(arab['VII'])
r1 = func(1, 0)
r2 = func(1, 1, 2)
chars = 'dog!'
167
CHAPTER 7. PUZZLES: INTERMEDIATE TO
168 PROFESSIONAL
char_1 = chars[-2]
char_2 = chars[chars.find('o')]
char_3 = chars[-1]
chars = 'bretsamaty'
word = chars[1:7][::-1]
print(word)
odds = [1, 3, 5, 7]
s = sum(odds) + max(odds) + min(odds)
print(s)
numbers = '1-2-3-4-5-6-7-8-9'
my_list = numbers.split('-')
my_list[::2] = (len(numbers) // 4 + 1) * 'X'
out = ''.join(my_list)
out = out.replace('X', '')
print(out)
print(format(0.1, '.5f'))
print(a == b)
odd = [1, 3, 5]
even = [2, 4, 6]
print(nums)
unknown = #input ??
str_ = unknown[0]
n = int('1101', 2)
print(n)
print(type_1 == type_2)
a = 1 > 0
CHAPTER 7. PUZZLES: INTERMEDIATE TO
184 PROFESSIONAL
if a or (1 / 0 == 0):
print('ok')
else:
print('nok')
n = 16
x = 0
while x < 3:
n /= 2
x += 1
print(n)
inc = lambda x : x + 1
print(inc(2))
7.15 Zip
# Elo 1721
print(len(l3))
7.15. ZIP 189
list_ = list(range(5))
func = lambda x: x % 2 == 0
ns = []
7.16. BASIC FILTERING 191
print(ns)
def func(x):
return x % 2 == 0
list_ = list(range(4))
incs = [x + 1 for x in list_]
print(incs)
encrypted = 'Dbftbs!fodszqujpo!jt!opu!tfdvsf"'
7.18. ENCRYPTION BY OBFUSCATION 195
decrypted = ''
for c in encrypted:
decrypted += chr(ord(c) - 1)
print(decrypted)
1
This encryption is called Caesar’s cipher because it was used
by Julius Caesar to encrypt his private conversations.
7.19. STRING DICTIONARY 197
dict_ = {
0: ' ', 3: 'eat', 2: 'apple',
4: 's', 1: 'Bob', 5: '.',
}
words = [1, 0, 3, 4, 0, 2, 4, 5]
sentence = ''''''
for w in words:
sentence += dict_[w]
print(sentence)
a = func_dict[0](3, -1)
7.20. FUNCTIONS ARE OBJECTS 199
b = func_dict[1](4.0, 0.5)
print(a + b)
customers = {
100: {'name': 'Alice', 'zip': 1234},
7.21. DICTIONARY OF DICTIONARIES 201
customers[101].clear()
print(len(customers))
zip_codes = {
3001: 'Dolomite',
3002: 'Goodwater',
3003: 'Montevallo',
7.22. SORTING DICTIONARY KEYS 203
3004: 'Shelby',
3000: 'Vance',
}
keys = list(zip_codes.keys())
keys.sort()
print(keys[0])
item_prices = {}
print(item_prices['tomato'])
item_prices = [
('car', 10000),
('boat', 7000),
('bike', 400),
('skateboard', 150),
('aircraft', 500000),
]
207
7.24. FILTERING WITH LIST COMPREHENSION
print(len(my_list))
prices = [
('banana', 1.5),
('apple', 2.0),
('bread', 2.0),
('milk', 1.0),
('fish', 3.5)
]
print(a)
speed = [
('car', 100),
('boat', 20),
('bike', 8),
('ski', 7),
('aircraft', 650),
]
7.26. MAXIMUM OF TUPLES 211
print(max(speed)[1])
speed = [
('car', 100),
('boat', 20),
('bike', 8),
('ski', 7),
('aircraft', 650),
]
del my_list
print(my_list)
set_ = set()
print(len(set_))
set_1 = {1, 2, 3, 4}
CHAPTER 7. PUZZLES: INTERMEDIATE TO
218 PROFESSIONAL
set_2 = {3, 4, 5, 6}
set_1 = set_1.intersection(set_2)
set_2 = set_2.difference(set_1)
print(len(set_1) + len(set_2))
numbers = [9, 2, 3, 3, 3, 7, 4, 5, 1, 6, 8]
def magic(l):
if len(l) <= 1:
CHAPTER 7. PUZZLES: INTERMEDIATE TO
220 PROFESSIONAL
return l
p = l[0]
return magic([x for x in l[1:] if x < p]) \
+ [p] \
+ magic([x for x in l[1:] if x >= p])
my_list = magic(numbers)
print(my_list)
7.32 Fibonacci
# Elo 1809
cache = {}
def fib(n):
if n < 0:
raise ValueError
if n == 1:
return 0
elif n == 2:
return 1
7.32. FIBONACCI 223
if not n in cache:
cache[n] = fib(n-1) + fib(n-2)
return cache[n]
fib(10)
print(len(cache))
Final Remarks
226
227
230
231
Coffee Break
NumPy
Slicing
9.1 Arithmetic
# Puzzle 1
x = 5 // -3.0 * 4
print(x)
235
236 CHAPTER 9. 50 BONUS WORKOUTS
9.2 Whitespace
# Puzzle 2
x = len('py\tpy\n')
print(x)
9.3 Modulo
# Puzzle 3
x = 0
while x < 4:
x += 1
if x % 2:
continue
print('$', end='')
else:
print('$', end='')
9.4 Tuple
# Puzzle 4
x = tuple(list('hi'))
print(x)
9.5 Dictionary
# Puzzle 5
d = dict([(i, i%3) for i in range(8)])
print(d[5])
9.6 Asterisk
# Puzzle 6
*x, y, z = 1, 2, 3, 4
*x, y = x, y, z
print(x[1])
9.7 Slicing 1
# Puzzle 7
t = [10, 20, 30, 40]
t[100:103] = [10]
print(t)
The result of the previous puzzle is: [10, 20, 30, 40,
10].
9.8 Slicing 2
t = [10, 20, 30, 40]
t[2:0] = [10]
print(t)
The result of the previous puzzle is: [10, 20, 10, 30,
40].
9.11 Exception
# Puzzle 11
try:
x = -9 ** 1/2
print(x)
except:
x = 8 * 2 // 5
print(x)
9.12 Insert
# Puzzle 12
t = [3, 4, 5, 6]
t.insert(0, t.pop(t.index(5)))
print(t)
9.14 Default
# Puzzle 14
c = 11
d = 12
func(10, c, d)
9.16 Global
# Puzzle 16
a = 10
def func(x=a):
global a
a += 1
print(x, a)
func(3)
9.17 Flow 1
# Puzzle 17
a = [10]
def func(a):
a.append(20)
print(a)
a = [2]
func(a)
9.18 Flow 2
# Puzzle 18
a = 1
b = [10]
func(a, b)
print(a in b)
9.19 Enumerate
# Puzzle 19
t = {}, {1}, {1,2}, {1:2}
myList = [k for k, v in enumerate(t) \
if isinstance(v, set)]
print(myList[0])
9.20 Reverse
# Puzzle 20
t = ['world', 'hello', 'python']
sorted_t = t.sort(reverse=True)
print(sorted_t)
9.22 Sorting++
# Puzzle 22
d = {3:10, 4:8, 3:9}
print(sorted(d, key=lambda x: d[x], reverse=True))
9.23 Indexing
# Puzzle 23
t = [[1, 2], [3, 4]]
t2 = t * 1
t[0][0] = 10
print(t2[0][0])
9.24 Count
# Puzzle 24
word = 'banana'
print(word.count('ana'))
9.25 Power
# Puzzle 25
x = 2 ** 1 ** 2 % -5
print(x)
9.26 Lambda
# Puzzle 26
t = ['python', 'puzzle', 'fun', 'java']
f = lambda lst: lst.pop(0)
g = lambda lst: lst.pop(1)
h = lambda lst: lst.pop(2)
d = {0:f, 1: g, 2: h}
x = d[f(t) > g(t)](t)
print(x)
9.27 Recursion
# Puzzle 27
def f(word):
if len(word) > 3:
return '*'
else:
word += '*'
return '*' + f(word)
print(f('*'))
9.28 Kwargs
# Puzzle 28
def f(a, b, c, d=4, e=5):
print(a + b + c + d + e)
x = word_dict('banana')['n']
print(x)
9.31 Print
# Puzzle 31
s = [('hello', 'world'), ('I', 'love', 'python')]
for x in s:
print(*x, sep='-', end='-')
9.32 Logic
# Puzzle 32
easy = True and False == True and False
print(easy)
b = 20
print(f(1))
9.34 Pass
# Puzzle 34
for i in range(5, -1, -1):
if i % 1 == 0:
pass
if i % 2 == 0:
continue
if i % 3 == 0:
break
print(i, end='-')
9.36 Zipzip
# Puzzle 36
a = [1, 3]
b = [2, 4, 6]
crazy = zip(*zip(a, b))
print(list(crazy))
The result of the previous puzzle is: [(1, 3), (2, 4)].
9.37 Comprehension
# Puzzle 37
t = [[i for i in range(j)] for j in range(4)]
print(t[2][1])
9.39 Max
# Puzzle 39
t = 'iPhone', 'Italy', '10', '2'
print(max(t))
9.40 Zip
# Puzzle 40
x = 1, 2
y = list(zip(x))
print(y[0])
9.41 Unpack
# Puzzle 41
a = [1]
b = [2, 4, 6]
crazy = zip(*zip(a, b))
y = list(crazy)
print(y[0])
9.42 Minimax
# Puzzle 42
def f(x, y):
x, y = min(x, y), max(x, y)
if y % x == 0:
return x
else:
return f(x, y % x)
print(f(16, 72))
9.43 Sort
# Puzzle 43
scores = [100, 84, 63, 97]
scores_sorted = scores.sort()
print(scores[0])
9.45 While
# Puzzle 45
i = 2
while i % 3:
i += 2
print('!', end='-')
print('!')
s = []
for x in pairs:
s += x
print(len(s))
9.48 Count
# Puzzle 48
ones = [(1),
(1,),
(1,1)]
print(ones.count(1))
9.49 Cut
# Puzzle 49
hair = 100
hair = 50
hair = cut(2, 20)
print(hair)
9.50 End
# Puzzle 50
if 1 < 2 is True:
print('nice', end=' ')
if 'A' < 'a' is True:
print('bravo', end=' ')
else:
print('great')