cribSheet python
cribSheet python
Creating Matrices
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
Matrix Properties
print(matrix.shape) # Output: (2, 3)
Basic Operations
result_matrix = matrix1 + matrix2
sub_matrix = matrix[1:, 0:2] # Extracts elements from row 1 onwards (all rows), columns 0 and
1 (exclusive)
max_value = np.max(matrix)
scaled_matrix = matrix * 2
total_sum = np.sum(matrix)
average_value = np.mean(matrix)
Python Cheat Sheet: Basic Functions
List:
Dictionary:
Strings:
Open:
with open("data.txt", "r") as file:
data = file.read() (Read entire file as string)
Read:
data = file.read(n) (Read n bytes/characters)
line = file.readline() (Read one line including newline character)
lines = file.readlines() (Read entire file line by line as a list)
Close: Included in with open statement (handles closing automatically)
Additional Notes:
"r" (read), "w" (write), and "a" (append) are the most common modes, but others exist for
specific use cases (see documentation for details).
read() is best for reading entire files or large chunks at once.
readline() is useful for processing files line by line, especially for very large files.
readlines() reads everything into memory at once, so be cautious with very large files.
Text mode (default) is for working with text files, while binary mode is needed for non-text files
(images, etc.).
Python Review
Operator Precedence
Type Operators
High **
Arithmetic *, /, //, %
+,-
Relation ==, !=, <=, >=, >, <
not
Logical
Low and
or
Python Review
ent
• while <condition>: ( ) [ ] , . : ' " #
comm
if/loop
• for v in <iterable>: e.g., range(start, num, step) slice
Decimal def
• Functions (def, return, call) Name’s context
- Built-in: abs, len, print, input, open, readline, readlines, write, join, append, strip
writelines, close, split ..
‣ Reserved words: import, True, None, with, as, False ..
Common Errors Reported Error
• Incorrect algorithm (or its coding) Debug incrementally, test each change
- Produces the wrong answer (sometimes or every time)
• Examples:
- Used unintended or improperly initialized variables (copy-paste?)
- Incorrect operator applied (relational, logical, indexing)
- Misunderstood order of evaluation (precedence, associativity of operators)
- Incorrect loop conditions (continuation/termination) or nesting
- Misunderstood what a function does, or how to control its operations