PYTHON NOTES
Here's a comprehensive guide covering the key concepts in Python from beginner to advanced,
including examples and explanations:
### 1. **Basic Syntax**
- Python is an interpreted, high-level language. Here's a simple Python program:
```python
print("Hello, World!")
```
- **Indentation** is crucial in Python, as it defines blocks of code.
### 2. **Variables and Data Types**
- **Variables** are used to store data. You can assign values to variables without declaring their
type:
```python
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_student = True # Boolean
```
- **Data Types**: Python supports several basic data types:
- `int`: Integer numbers
- `float`: Floating-point numbers
- `str`: Strings
- `bool`: Boolean values (`True` or `False`)
### 3. **Conditional Statements**
- Conditional statements allow you to execute code based on conditions.
PYTHON NOTES
```python
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
```
- **Elif**: Multiple conditions can be checked using `elif`:
```python
marks = 85
if marks >= 90:
print("A Grade")
elif marks >= 75:
print("B Grade")
else:
print("C Grade")
```
### 4. **Type Casting**
- Type casting allows you to convert variables from one type to another:
```python
x = 5 # int
y = float(x) # Cast to float
z = str(x) # Cast to string
```
### 5. **Exceptions**
- Python uses `try` and `except` blocks to handle exceptions (errors).
PYTHON NOTES
```python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
```
- **Finally** block: Code inside the `finally` block will run regardless of whether an exception
occurs.
```python
try:
file = open("example.txt")
except FileNotFoundError:
print("File not found.")
finally:
print("This runs no matter what.")
```
### 6. **Functions**
- Functions are reusable blocks of code.
```python
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
```
- **Arguments and Return Values**: Functions can take arguments and return values.
PYTHON NOTES
```python
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
```
### 7. **Built-in Functions**
- Python provides many built-in functions, such as:
```python
print(len("Hello")) # Output: 5
print(max(10, 20, 5)) # Output: 20
print(sum([1, 2, 3, 4])) # Output: 10
```
### 8. **Lists**
- **Lists** are ordered, mutable collections.
```python
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry', 'orange']
```
PYTHON NOTES
### 9. **Tuples**
- **Tuples** are ordered, immutable collections.
```python
point = (1, 2)
print(point[0]) # Output: 1
# Tuples cannot be modified
# point[0] = 3 # This will raise an error
```
### 10. **Sets**
- **Sets** are unordered collections of unique elements.
```python
numbers = {1, 2, 3, 4, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5}
numbers.add(6)
print(numbers) # Output: {1, 2, 3, 4, 5, 6}
numbers.remove(4)
print(numbers) # Output: {1, 2, 3, 5, 6}
```
### 11. **Dictionaries**
- **Dictionaries** are unordered collections of key-value pairs.
```python
student = {"name": "Alice", "age": 20, "grade": "A"}
PYTHON NOTES
print(student["name"]) # Output: Alice
student["age"] = 21 # Update value
print(student) # Output: {'name': 'Alice', 'age': 21, 'grade': 'A'}
student["major"] = "Computer Science" # Add new key-value pair
print(student) # Output: {'name': 'Alice', 'age': 21, 'grade': 'A', 'major': 'Computer Science'}
```
### 12. **Advanced Concepts**
- **List Comprehensions**: A concise way to create lists.
```python
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
```
- **Lambda Functions**: Anonymous functions defined using `lambda`.
```python
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
```
- **Map, Filter, Reduce**:
- `map` applies a function to all items in an input list.
```python
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares) # Output: [1, 4, 9, 16]
PYTHON NOTES
```
- `filter` filters items based on a condition.
```python
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums) # Output: [2, 4]
```
- `reduce` applies a rolling computation to sequential pairs of values in a list (from the `functools`
module).
```python
from functools import reduce
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 24
```
This guide should give you a solid foundation in Python, from the basics to more advanced concepts.
Let me know if you'd like more detailed explanations or examples!
PYTHON NOTES
Here's a comprehensive guide on Data Structures and Algorithms in Python, covering arrays, linked
lists, heaps, stacks, queues, hash tables, binary search trees, recursion, and sorting algorithms. This
guide includes both explanations and example programs.
---
### 1. **Arrays**
- Arrays are collections of items stored at contiguous memory locations. Python uses lists to
implement arrays.
```python
# Creating an array (list in Python)
arr = [1, 2, 3, 4, 5]
# Accessing elements
print(arr[0]) # Output: 1
# Modifying elements
arr[1] = 20
print(arr) # Output: [1, 20, 3, 4, 5]
# Iterating through the array
for i in arr:
print(i)
```
### 2. **Linked Lists**
- A linked list is a linear data structure where elements are stored in nodes, with each node pointing
to the next node.
```python
class Node:
PYTHON NOTES
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data, end=" -> ")
cur_node = cur_node.next
print("None")
# Example usage
llist = LinkedList()
llist.append(1)
llist.append(2)
llist.append(3)
llist.print_list() # Output: 1 -> 2 -> 3 -> None
PYTHON NOTES
```
### 3. **Heaps**
- A heap is a special tree-based data structure that satisfies the heap property. Python’s `heapq`
module provides an implementation of heaps.
```python
import heapq
# Min-heap example
heap = []
heapq.heappush(heap, 10)
heapq.heappush(heap, 5)
heapq.heappush(heap, 20)
print(heapq.heappop(heap)) # Output: 5 (smallest element)
print(heap) # Output: [10, 20]
```
### 4. **Stacks**
- A stack is a linear data structure that follows the LIFO (Last In, First Out) principle.
```python
stack = []
# Push operation
stack.append(1)
stack.append(2)
stack.append(3)
# Pop operation
PYTHON NOTES
print(stack.pop()) # Output: 3
print(stack) # Output: [1, 2]
```
### 5. **Queues**
- A queue is a linear data structure that follows the FIFO (First In, First Out) principle.
```python
from collections import deque
queue = deque()
# Enqueue operation
queue.append(1)
queue.append(2)
queue.append(3)
# Dequeue operation
print(queue.popleft()) # Output: 1
print(queue) # Output: deque([2, 3])
```
### 6. **Hash Tables**
- Hash tables (dictionaries in Python) store key-value pairs for efficient lookup.
```python
# Creating a hash table (dictionary in Python)
hash_table = {}
# Inserting key-value pairs
hash_table["name"] = "Alice"
PYTHON NOTES
hash_table["age"] = 25
# Accessing values by key
print(hash_table["name"]) # Output: Alice
# Checking if a key exists
if "age" in hash_table:
print("Age is in the hash table.")
```
### 7. **Binary Search Trees (BST)**
- A binary search tree is a tree data structure in which each node has at most two children, and for
each node, the left child's value is less than the parent, and the right child's value is greater.
```python
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
if key < root.val:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
def inorder(root):
PYTHON NOTES
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)
# Example usage
root = Node(10)
insert(root, 5)
insert(root, 20)
insert(root, 3)
inorder(root) # Output: 3 5 10 20
```
### 8. **Recursion**
- Recursion is a method where the solution to a problem depends on solving smaller instances of
the same problem.
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
```
- **Example: Fibonacci Sequence**
```python
def fibonacci(n):
PYTHON NOTES
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # Output: 8
```
### 9. **Sorting Algorithms**
- **Bubble Sort**
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr) # Output: [11, 12, 22, 25, 34, 64, 90]
```
- **Merge Sort**
```python
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
PYTHON NOTES
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
arr = [12, 11, 13, 5, 6, 7]
merge_sort(arr)
print("Sorted array:", arr) # Output: [5, 6, 7, 11, 12, 13]
```
PYTHON NOTES
- **Quick Sort**
```python
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
def quick_sort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quick_sort(arr, low, pi-1)
quick_sort(arr, pi+1, high)
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quick_sort(arr, 0, n-1)
print("Sorted array:", arr) # Output: [1, 5, 7, 8, 9, 10]
```
This guide covers the essentials of data structures and algorithms in Python, from basic to advanced
concepts. Let me know if you need further details or additional examples!