python_cheatsheet_2
python_cheatsheet_2
A map(func, iter) Executes the function on all elements of list(map(lambda x: x[0], ['red', ['r', 'g', 'b']
D the iterable 'green', 'blue']))
V
A map(func, i1, ..., Executes the function on all k elements of list(map(lambda x, y: str(x) + ' ' + ['0 apples', '2
ik) the k iterables y + 's' , [0, 2, 2], ['apple', oranges', '2
N
C 'orange', 'banana'])) bananas']
E
string.join(iter) Concatenates iterable elements ' marries '.join(list(['Alice', 'Alice marries Bob'
D separated by string 'Bob']))
F filter(func, Filters out elements in iterable for which list(filter(lambda x: True if x>17 [18]
U iterable) function returns False (or 0) else False, [1, 15, 17, 18]))
N
C string.strip() Removes leading and trailing print(" \n \t 42 \t ".strip()) 42
T whitespaces of string
I
O sorted(iter) Sorts iterable in ascending order sorted([8, 3, 2, 42, 5]) [2, 3, 5, 8, 42]
N
sorted(iter, Sorts according to the key function in sorted([8, 3, 2, 42, 5], key=lambda [42, 2, 3, 5, 8]
S
key=key) ascending order x: 0 if x==42 else x)
zip(i1, i2, ...) Groups the i-th elements of iterators i1, i2, list(zip(['Alice', 'Anna'], ['Bob', [('Alice', 'Bob'),
… together 'Jon', 'Frank'])) ('Anna', 'Jon')]
Unzip Equal to: 1) unpack the zipped list, 2) zip list(zip(*[('Alice', 'Bob'), [('Alice', 'Anna'),
the result ('Anna', 'Jon')] ('Bob', 'Jon')]
enumerate(iter) Assigns a counter value to each element list(enumerate(['Alice', 'Bob', [(0, 'Alice'), (1,
of the iterable 'Jon'])) 'Bob'), (2, 'Jon')]
T python -m http.server Share files between PC and phone? Run command in PC’s shell. <P> is any port number 0–65535. Type < IP address of
R <P> PC>:<P> in the phone’s browser. You can now browse the files in the PC directory.
I
C Read comic import antigravity Open the comic series xkcd in your web browser
K
S
Zen of Python import this '...Beautiful is better than ugly. Explicit is ...'
Unpacking arguments Use a sequence as function arguments def f(x, y, z): return x + y * z
via asterisk operator *. Use a dictionary f(*[1, 3, 4]) 13
(key, value) via double asterisk operator ** f(**{'z' : 4, 'x' : 1, 'y' : 3}) 13
Extended Unpacking Use unpacking for multiple assignment a, *b = [1, 2, 3, 4, 5] a = 1
feature in Python b = [2, 3, 4, 5]
Merge two dictionaries Use unpacking to merge two dictionaries x={'Alice' : 18} z = {'Alice': 18,
into a single one y={'Bob' : 27, 'Ann' : 22} 'Bob': 27, 'Ann': 22}
z = {**x,**y}
Python Cheat Sheet: 14 Interview Questions
“A puzzle a day to learn, code, and play” →
*FREE* Python Email Course @ http://bit.ly/free-python-course
Question Code Question Code
Check if list l = [3, 3, 4, 5, 2, 111, 5] Get missing def get_missing_number(lst):
contains print(111 in l) # True number in return set(range(lst[len(lst)-1])[1:]) - set(l)
integer x [1...100] l = list(range(1,100))
l.remove(50)
print(get_missing_number(l)) # 50
Check if two def is_anagram(s1, s2): Find max l = [4, 3, 6, 3, 4, 888, 1, -11, 22, 3]
strings are return set(s1) == set(s2) and min in print(max(l)) # 888
anagrams print(is_anagram("elvis", "lives")) # True unsorted list print(min(l)) # -11
a.ndim The ndim attribute is equal to the length of the shape tuple. print(np.ndim(a)) # 2
* The asterisk (star) operator performs the Hadamard product, a = np.array([[2, 0], [0, 2]])
i.e., multiplies two matrices with equal shape element-wise. b = np.array([[1, 1], [1, 1]])
print(a*b) # [[2 0] [0 2]]
np.matmul(a,b), a@b The standard matrix multiplication operator. Equivalent to the print(np.matmul(a,b))
@ operator. # [[2 2] [2 2]]
np.arange([start, ]stop, Creates a new 1D numpy array with evenly spaced values print(np.arange(0,10,2))
[step, ]) # [0 2 4 6 8]
np.linspace(start, stop, Creates a new 1D numpy array with evenly spread elements print(np.linspace(0,10,3))
num=50) within the given interval # [ 0. 5. 10.]
np.average(a) Averages over all the values in the numpy array a = np.array([[2, 0], [0, 2]])
print(np.average(a)) # 1.0
<slice> = <val> Replace the <slice> as selected by the slicing operator with a = np.array([0, 1, 0, 0, 0])
the value <val>. a[::2] = 2
print(a) # [2 1 2 0 2]
np.diff(a) Calculates the difference between subsequent values in fibs = np.array([0, 1, 1, 2, 3, 5])
NumPy array a print(np.diff(fibs, n=1))
# [1 0 1 1 2]
np.sort(a) Creates a new NumPy array with the values from a a = np.array([10,3,7,1,0])
(ascending). print(np.sort(a))
# [ 0 1 3 7 10]
np.argsort(a) Returns the indices of a NumPy array so that the indexed a = np.array([10,3,7,1,0])
values would be sorted. print(np.argsort(a))
# [4 3 1 2 0]
np.argmax(a) Returns the index of the element with maximal value in the a = np.array([10,3,7,1,0])
NumPy array a. print(np.argmax(a)) # 0
np.nonzero(a) Returns the indices of the nonzero elements in NumPy array a = np.array([10,3,7,1,0])
a. print(np.nonzero(a)) # [0 1 2 3]
Python Cheat Sheet: Object Orientation Terms
“A puzzle a day to learn, code, and play” → Visit f inxter.com
Description Example
Class A blueprint to create o bjects. It defines the data (attributes) and functionality class Dog:
(methods) of the objects. You can access both attributes and methods via
the dot notation. # class attribute
is_hairy = True
Object A piece of encapsulated data with functionality in your Python program that
(=instance) efinition. Often, an object corresponds to a
is built according to a c lass d # constructor
def __init__(self, name):
thing in the real world. An example is the object "Obama" that is created
# instance attribute
according to the class definition "Person". An object consists of an arbitrary
self.name = name
number of a ttributes a
nd m
ethods, e ncapsulated w
ithin a single unit.
# method
Instantiation bject of a c lass. This is done with the
The process of creating an o
def bark(self):
constructor method __init__(self, …). print("Wuff")
Self The first argument when defining any method is always the s elf argument. print(bello.name)
"bello"
n which you call the m
This argument specifies the i nstance o ethod.
self gives the Python interpreter the information about the concrete print(paris.name)
"paris"
instance. To define a method, you use s elf to modify the instance
attributes. But to call an instance method, you do not need to specify s
elf.
class Cat:
Encapsulation Binding together data and functionality that manipulates the data.
# method overloading
Attribute A variable defined for a class (class attribute) or for an object (instance attribute). You def miau(self, times=1):
use attributes to package data into enclosed units (class or instance). print("miau " * times)
Class (=class variable, static variable, static attribute) A variable that is created fifi = Cat()
attribute statically in the class definition and that is shared by all class objects.
fifi.miau()
Instance A variable that holds data that belongs only to a single instance. Other instances do "miau "
attribute not share this variable (in contrast to class attributes). In most cases, you create an
(=instance instance attribute x in the constructor when creating the instance itself using the self fifi.miau(5)
variable) "miau miau miau miau miau "
keywords (e.g. self.x = <val>).
# Dynamic attribute
fifi.likes = "mice"
Dynamic An instance attribute that is defined dynamically during the execution of the program print(fifi.likes)
attribute and that is not defined within any method. For example, you can simply add a new "mice"
attribute neew to any object o by calling o.neew = <val>.
# Inheritance
Method You may want to define a method in a way so that there are multiple options class Persian_Cat(Cat):
overloading to call it. For example for class X, you define a method f(...) that can be called classification = "Persian"
in three ways: f(a), f(a,b), or f(a,b,c). To this end, you can define the method
mimi = Persian_Cat()
with default parameters (e.g. f(a, b=None, c=None).
print(mimi.miau(3))
"miau miau miau "
Inheritance Class A can inherit certain characteristics (like attributes or methods) from class B.
For example, the class "Dog" may inherit the attribute "number_of_legs" from the
class "Animal". In this case, you would define the inherited class "Dog" as follows: print(mimi.classification)
"class Dog(Animal): ..."