Python Cheat Sheet
Libraries
Before you can use libraries, you need to import them. For maths:
import maths
For random:
import random
If the library name i slong, such as for plotting, you can set a shortened name:
import matplotlib.pyplot as plot
Useful random functions
To generate a random number, n, in the range 0 ≤ n < 1:
n = random.random()
To generate a random integer, n, in the range a ≤ n ≤ b:
n = random.randint(a,b)
Therefore, a function for rolling a standard six-sided die is:
roll = random.randint(1,6)
Lists / Arrays
n number of data points can be stored in lists, where each data point is given an index address. The first term has address [0], and the last term has address [n-1]. Indexing can be done in negative: in this case, the last term has address [-1] and the first term has address [n].
Defining Lists
To define lists manually:
Age = [18, 18, 19, 18, 17 ... ]
Colour = ['Blue', 'Green', 'Yellow' ...]
Note that you need to put strings in quote marks.
To define lists automatically as a list of integers from a range of a to b:
R = range(a, b+1)
A = []
for members in R:
A = A + [members]
To generate a list from a series of values, for example a set of random numbers:
for members in A:
members = random.randint(1,6)
die.append(members)
Integer Lists
To sum all the terms in a list:
for members in List:
members = sum(List)
To apply maths on every member of a list, L:
Lx2 = list(map(lambda x: x * 2, L))
Lplus1 = list(map(lambda x: x + 1, L))
Lsquared = list(map(lambda x: x ** 2, L))
To multiply all the numbers in a list together:
def multiply(List):
total = 1
for n in List:
total *= n
return total
print(multiply((List)))
To swap two elements in a list:
L = [1,2,3,4,5]
#to swap 2 and 3:
temp = L[1]
L[1] = L[2]
L[2] = temp
Searching Lists
To search for a value in a list, there are two options. The first is to use a for loop - this is used when you want to carry on searching the list even after you found the value:
List = #define list
find = input()
# Convert to integer if necessary
found = False
for members in List:
if members == find:
found = True
print(found)
The second is to use a while loops - this will stop counting either when you reach the value, or when the whole list has been counted:
List = #define list
N = len(List)
find = input()
# Convert to integer if necessary
found = False
count = 0
while (not found) and count < N:
if List[count] == find:
found = True
else:
count = count + 1
print(found)
Boolean Operations
The if-else function is used to test boolean outcomes (where the outcome is either 'yes' or 'no').
a == b a equals b
a != b a does not equal b
a < b a is less than b
a > b a is greater than b
a <= b a is smaller than or equal to b
a => b a is greater than or equal to b
A nice example is rolling two dice. This requires two loops, the first tests for a draw, the second for a winner.
import random as rn
#Setting up rolling functions
Die1 = rn.randint(1,6)
Die2 = rn.randint(1,6)
#Rolling the dice
print('Die 1 lands on a', Die1)
print('Die 2 lands on a', Die2)
if Die1 == Die2:
#it is a draw
print('It is a draw.')
else:
if Die1 < Die2:
#Die2 wins
print('Die 2 wins.')
else:
#Die1 wins
print('Die 1 wins.')
Quick Functions
Type function
To find what type of variable a variable is:
Remainder Function
To find the remainder of a division:
# a is the numerator
# b is the denominator
# r is the remainder
r = a//b
print(r)
I/O Files
Data can be input directly or indirectly to a code. Direct inputs are provided interactively, while the programme is running (e.g. using a keyboard and the input() function). Indirect inputs are when data is read from a predefined location, such as a file.
Writing to Files
Just like libraries, files need to be uploaded before they can be accessed:
f = open('FileName.txt', 'w')
This opens the file 'FileName.txt' to write to it, and assigns it to variable f. To write something to the file, for example a number of strings, use the write command:
# To add strings a and b to the file on separate lines:
f.write(str(a) + '\n')
f.write(str(b) + '\n')
To write from a list:
# To add a list to a file, with each element on a new line:
for item in a:
f.write(str(item) + '\n')
To create a file with numbers from 1 to 100:
f = open('Numbers100.txt', 'w')
R = range(1, 101)
for i in R:
f.write(str(i) + '\n')
f.close()
Reading from Files
Instead of using a 'w', an 'r' represents reading:
f = open('FileName.txt', 'r')
By default, the program will read a file exactly as it is:
f = open('FileName.txt, 'r')
a = f.read()
f.close()
print(a)
If, however, you want to compile all the lines into a list, use the .readlines command:
f = open('FileName.txt', 'r')
a = f.readlines()
f.close
print(a)
This produces a list of strings with operators '\n' attached. The new line trail can be removed using a strip function:
f = open('FileName.txt', 'r')
a = f.readlines()
f.close()
b = []
for items in a:
b = b + [items.rstrip()]
print(b)
Creating a List of Integers from a .txt File
f = open('IntegerList.txt', 'r')
a = f.readlines()
f.close()
b = []
for items in a:
b = b + [int(items.rstrip())]
Closing Files
When finished with a file, it needs to be closed (this is like saving it):
f.close()
Matrices
Python is a very powerful tool for computing data stored in matrices.
Defining a Matrix from a List
n is the number of rows
m is the number of columns
'List' is... the list
def Matrix(n, m, List):
row = []
matrix = [0 for height in range(0, n)
for p in range(0, n, 1):
for i in range((p*m), ((p+1)*m)):
row = row + [List[i]]
matrix[p] = row
row = []
return matrix
Finding the Transpose of a Matrix
M is the matrix we want to transpose
n is the number of rows in M
m is the number of columns in M
def Transpose(n, m, M):
#M is an nxm matrix
row = []
transpose = [0 for height in range(0, m)]
#B is the column number
for B in range(0, m):
#A is the row number
for A in range(0, n):
row = row + [M[A][B]}
transpose[B] = row
row = []
return transpose
Finding the Product of Two Matrices
def MatrixMult(A, B):
#A and B are the matrices, AB = C
if len(A[0]) == len(B):
add = 0
C = [[0 for width in range(len(B[0]))] for height in range(len(A))[
for x in range(0, len(A)):
for y in range(0, len(B[0])):
for z in range(0, len(A[0])):
add = add + (A[x][z]*B[z][y])
C[x][y] = add
add = 0
return C
else:
return
Approximating Pi
import matplotlib.pyplot as plot
import random as rn
print('Input n:')
n = input()
n=int(n)
r = range(1,n)
xout = []
xin = []
yout = []
yin = []
pointsinside = 0
pointsoutside = 0
for c in r:
x = rn.random()-0.5
y = rn.random()-0.5
if(x**2 + y**2 < 0.25):
xin = xin + [x]
yin = yin + [y]
else:
xout = xout + [x]
yout = yout + [y]
pi = len(xin)*4/n
print('Pi =', pi)
plot.scatter(xin, yin, color = 'green')
plot.scatter(xout, yout, color = 'black')
TEST FOR jqMATH
$$y-y_0=m(x-x_0)$$
$$y-y_0=m(x-x_0)$$
$$ax^2$$
is there an equation here? \( ax^2 \) I wonder if it works
留言