0% found this document useful (0 votes)
14 views

cribSheet python

Uploaded by

iitiantejashvi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

cribSheet python

Uploaded by

iitiantejashvi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Basic functionalities for numpy

Creating Matrices
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)

zeros_matrix = np.zeros((3, 4)) # Creates a 3x4 matrix of zeros


print(zeros_matrix)

ones_matrix = np.ones((2, 2)) # Creates a 2x2 matrix of ones


print(ones_matrix)

identity_matrix = np.eye(3) # Creates a 3x3 identity matrix


print(identity_matrix)

random_matrix = np.random.rand(2, 3) # Creates a 2x3 matrix of random floats


print(random_matrix)

Matrix Properties
print(matrix.shape) # Output: (2, 3)

print(matrix.dtype) # Output: int32 (assuming integers were used)

Basic Operations
result_matrix = matrix1 + matrix2

result_matrix = matrix1 * 2 # Scalar multiplication

comparison_matrix = matrix1 > matrix2

combined_matrix = (matrix1 > 2) & (matrix2 < 5)

matrix[0, 1] = 10 # Assigns 10 to the element at row 0, column 1


Indexing and Slicing
element = matrix[1, 2] # Accesses the element at row 1, column 2

sub_matrix = matrix[1:, 0:2] # Extracts elements from row 1 onwards (all rows), columns 0 and
1 (exclusive)

Multiplciation using different ways

product_matrix = np.dot(matrix1, matrix2) #dot product

Other operations on matrices


min_value = np.min(matrix)

max_value = np.max(matrix)

column_wise_min = np.min(matrix, axis=0)

row_wise_max = np.max(matrix, axis=1)

scaled_matrix = matrix * 2

element_wise_product = matrix1 * matrix2

total_sum = np.sum(matrix)

average_value = np.mean(matrix)
Python Cheat Sheet: Basic Functions
List:

Create: my_list = [1, 2, 3]


Append: my_list.append(4) (add to the end)
Insert: my_list.insert(1, 2.5) (at specific index)
Remove: my_list.remove(2) (by value)
Pop: my_list.pop() (remove and return last element)
Length: len(my_list)
Access: my_list[0] (first element)
Slicing: my_list[1:3] (elements from index 1 to 2 (not including 3))
Loop: for item in my_list:
print(item)
sorted(my_list) - sort the list

Dictionary:

Create: my_dict = {"name": "Alice", "age": 30}


Access: my_dict["name"] (by key)
Update: my_dict["age"] = 31
Check Key: if "age" in my_dict:
Get Keys/Values: my_dict.keys(), my_dict.values()
Loop: for key, value in my_dict.items(): print(key, value)

Strings:

Concatenate: name = "Alice " + "Bob"


Slicing: name[0:3] (characters from index 0 to 2)
Upper: name.upper(),
Lower : name.lower()
Split: name_list = name.split(".") (split by dot - “.”)
Strip: clean_name = name.strip() (remove leading/trailing whitespaces)
File I/O:

Open:
with open("data.txt", "r") as file:
data = file.read() (Read entire file as string)

with open("data.txt", "w") as file:


file.write("Hello World!") (Write to file, overwrites existing content)

with open("data.txt", "a") as file:


file.write("\nNew Line") (Append to file)

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

‣ Objects and their names

‣ Actions Assignment Arith. op. Relational op. Logical op.


• Operators: = ** * / // % + — Aop= < > <= >= == != not and or

Operator Precedence
Type Operators
High **
Arithmetic *, /, //, %
+,-
Relation ==, !=, <=, >=, >, <
not
Logical
Low and
or
Python Review

‣ Objects and their names

‣ Actions Assignment Arith. op. Relational op. Logical op.


• Operators: = ** * / // % + — Aop= < > <= >= == != not and or
Function parameters
‣ Control flow
Precedence String
Tuple List maker
• if/elif/else <condition>: logical expression
Ordinal item

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

‣ Translation-time error Look out

• Syntax error: unrecognizable words, malformed constructs and paragraphs


- ((unmatched), a ++ b, missing ‘:’ ..
- Wrong indentation
• Semantic error:
- Wrong operation or type
- Uninitialized/Unavailable name used (mispelt?)
- Wrong number of operands/partameters used
‣ Run-time error:
• Unsupported/Unexpected operations (Exceptions) …
Common Errors Unreported Errors

‣ Program-logic error Look out for hidden assumptions

• 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

You might also like