Here
Here
Here's a comprehensive guide covering the key concepts in Python from beginner to advanced,
including examples and explanations:
```python
print("Hello, World!")
```
- **Variables** are used to store data. You can assign values to variables without declaring their
type:
```python
x = 10 # Integer
y = 3.14 # Float
```
- `str`: Strings
```python
age = 18
else:
```
```python
marks = 85
print("A Grade")
print("B Grade")
else:
print("C Grade")
```
- Type casting allows you to convert variables from one type to another:
```python
x = 5 # int
```
### 5. **Exceptions**
```python
try:
result = 10 / 0
except ZeroDivisionError:
```
- **Finally** block: Code inside the `finally` block will run regardless of whether an exception
occurs.
```python
try:
file = open("example.txt")
except FileNotFoundError:
finally:
```
### 6. **Functions**
```python
def greet(name):
print(greet("Alice"))
```
- **Arguments and Return Values**: Functions can take arguments and return values.
PYTHON NOTES
```python
return a + b
result = add(5, 3)
print(result) # Output: 8
```
```python
print(len("Hello")) # Output: 5
```
### 8. **Lists**
```python
fruits.append("orange")
fruits.remove("banana")
```
PYTHON NOTES
### 9. **Tuples**
```python
point = (1, 2)
print(point[0]) # Output: 1
```
```python
numbers = {1, 2, 3, 4, 4, 5}
numbers.add(6)
numbers.remove(4)
```
```python
print(student) # Output: {'name': 'Alice', 'age': 21, 'grade': 'A', 'major': 'Computer Science'}
```
```python
```
```python
add = lambda x, y: x + y
```
```python
nums = [1, 2, 3, 4]
```
```python
```
- `reduce` applies a rolling computation to sequential pairs of values in a list (from the `functools`
module).
```python
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
arr = [1, 2, 3, 4, 5]
# Accessing elements
print(arr[0]) # Output: 1
# Modifying elements
arr[1] = 20
for i in arr:
print(i)
```
- 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
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
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:
cur_node = cur_node.next
print("None")
# Example usage
llist = LinkedList()
llist.append(1)
llist.append(2)
llist.append(3)
```
### 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)
```
### 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
```
### 5. **Queues**
- A queue is a linear data structure that follows the FIFO (First In, First Out) principle.
```python
queue = deque()
# Enqueue operation
queue.append(1)
queue.append(2)
queue.append(3)
# Dequeue operation
print(queue.popleft()) # Output: 1
```
- Hash tables (dictionaries in Python) store key-value pairs for efficient lookup.
```python
hash_table = {}
hash_table["name"] = "Alice"
PYTHON NOTES
hash_table["age"] = 25
if "age" in hash_table:
```
- 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:
self.left = None
self.right = None
self.val = key
if root is None:
return Node(key)
else:
return root
def inorder(root):
PYTHON NOTES
if root:
inorder(root.left)
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)
```
```python
def fibonacci(n):
PYTHON NOTES
if n <= 1:
return n
else:
print(fibonacci(6)) # Output: 8
```
- **Bubble Sort**
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
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
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
arr[k] = L[i]
i += 1
k += 1
arr[k] = R[j]
j += 1
k += 1
merge_sort(arr)
```
PYTHON NOTES
- **Quick Sort**
```python
pivot = arr[high]
i = low - 1
i += 1
return i+1
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quick_sort(arr, 0, n-1)
```
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!