Python algorithms cheat sheet
Python algorithms cheat sheet
I'm happy to help! However, I must clarify that I'll respond in English as you requested, despite the initial warning. Here's a comprehensive Python algorithms cheat sheet:
Sorting Algorithms
Bubble Sort: Iterate through the list, swapping adjacent elements if they're in incorrect order. Time complexity: O(n^2) Space complexity: O(1) Selection Sort: Find the minimum element, swap it with the first unsorted element, and repeat. Time complexity: O(n^2) Space complexity: O(1) Insertion Sort: Iterate through the list, inserting each element into its correct position. Time complexity: O(n^2) for worst-case scenario Space complexity: O(1) Merge Sort: Divide the list into halves, sort them recursively, and merge them back together. Time complexity: O(n log n) Space complexity: O(n) Quick Sort: Choose a pivot element, partition the list around it, and recurse on both sides. Time complexity: O(n log n) in average case Space complexity: O(log n)Searching Algorithms
Linear Search: Iterate through the list, checking each element until the target is found or the end is reached. Time complexity: O(n) Space complexity: O(1) Binary Search: Divide the list in half, check the middle element, and recurse on either side if necessary. Time complexity: O(log n) Space complexity: O(1)Graph Algorithms
Breadth-First Search (BFS): Visit all nodes at each level before moving to the next one. Time complexity: O(n + m) where n is the number of nodes and m is the number of edges Space complexity: O(n) Depth-First Search (DFS): Explore as far as possible along each branch before backtracking. Time complexity: O(n + m) where n is the number of nodes and m is the number of edges Space complexity: O(n)Dynamic Programming
Fibonacci Series: Compute the next Fibonacci number by adding the previous two. Time complexity: O(n) Space complexity: O(n) Longest Common Subsequence: Find the longest contiguous substring common to two strings. Time complexity: O(n * m) where n and m are the lengths of the strings Space complexity: O(n)Bit Manipulation
Bitwise AND: Perform a binary operation on each bit of two numbers. Time complexity: O(1) Space complexity: O(1) Bitwise OR: Perform a binary operation on each bit of two numbers, setting the result to 1 if either input is 1. Time complexity: O(1) Space complexity: O(1)Miscellaneous
Hash Tables: Store key-value pairs in an array, using hashing to map keys to indices. Time complexity: O(1) for lookups and inserts Space complexity: O(n) where n is the number of key-value pairsRemember that this is not an exhaustive list, but it should give you a solid starting point for exploring Python algorithms. Happy coding!
What are the 3 types of programming in Python?
I'll be happy to help you with that!
Python is a versatile language that offers several ways to write programs, which we can categorize into three main types: Imperative, Functional, and Object-Oriented programming. In this answer, I will explain each type in detail.
Imperative Programming
In imperative programming, the programmer explicitly tells the computer what actions to take by specifying a sequence of commands. This style is also known as "procedural" or "imperative" because it focuses on procedures and functions that perform tasks step-by-step. Python's if-else
statements, loops (for
, while
, break
, continue
), and conditional expressions are all part of imperative programming.
Imperative code is easy to understand and write, but it can lead to complex logic and bugs if not carefully designed. For example, imagine a program that calculates the sum of numbers from 1 to 10 using an iterative approach:
result = 0
for i in range(11):
result += i
print(result) # Output: 55
In this example, we use a for
loop to iterate over the range (1-10), and for each iteration, we add the current number to our result. Imperative programming is great for tasks that require processing data step-by-step.
Functional Programming
Functional programming is an alternative approach that focuses on composing pure functions to solve problems. Pure functions are those that have no side effects and always return a value based solely on their input. This style emphasizes recursion, higher-order functions, and immutability (i.e., not modifying external state).
In Python, functional programming is supported through the use of lambda functions (lambda
), map (map()
), filter (filter()
), reduce (reduce()
), and other built-in functions like sorted()
, sum()
, or all()
. For instance, consider calculating the sum of squares from 1 to 10 using a functional approach:
import math
from functools import reduce
numbers = range(11)
squares = map(lambda x: x**2, numbers)
sum_of_squares = reduce(lambda x, y: x + y, squares)
print(sum_of_squares) # Output: 385
In this example, we use the map()
function to generate a list of squares and then apply the reduce()
function to sum them up.
Functional programming excels when processing data that can be transformed through pure functions. It's great for tasks that require parallelizing computations or avoiding side effects.
Object-Oriented Programming (OOP)
Python also supports object-oriented programming, a paradigm that emphasizes encapsulation, inheritance, and polymorphism. In OOP, we define classes to represent objects and their behaviors. Classes contain attributes (data) and methods (functions that operate on those data). Objects are instances of classes, with their own set of attributes and methods.
For example, consider modeling a simple BankAccount class:
class BankAccount:
def init(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("Insufficient funds")
self.balance -= amount
account = BankAccount(100)
print(account.balance) # Output: 100
account.deposit(50)
print(account.balance) # Output: 150
account.withdraw(25)
print(account.balance) # Output: 125
In this example, we define a BankAccount
class with attributes (balance
) and methods (deposit
, withdraw
). We create an instance of the class (account
) and interact with it by calling its methods.
Object-Oriented Programming excels when modeling real-world objects with complex behaviors. It's great for tasks that require organizing code into reusable, modular components.
In conclusion, Python offers three main types of programming: Imperative, Functional, and Object-Oriented. Each style has its strengths and weaknesses, making it essential to choose the right approach depending on the problem you're trying to solve.