Categories
Python
C++
MATLAB
C
Assembly
Java
Rust
Code Snippets & Examples
Explore ready-to-use coding resources.
Quick Sort with Detailed Logging
import time
def quick_sort(arr, depth=0):
indent = " " * depth
print(f"{indent}Sorting: {arr}")
if len(arr) <= 1:
print(f"{indent}Returning sorted: {arr}")
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
sorted_left = quick_sort(left, depth + 1)
sorted_right = quick_sort(right, depth + 1)
sorted_arr = sorted_left + middle + sorted_right
print(f"{indent}Merged: {sorted_arr}")
return sorted_arr
# Test the function
arr = [34, 7, 23, 32, 5, 62]
sorted_arr = quick_sort(arr)
print("Final sorted array:", sorted_arr)
Neural Network with Custom Activation
import tensorflow as tf
import numpy as np
# Custom activation function
def custom_activation(x):
return tf.nn.relu(x) - 0.1 * tf.nn.sigmoid(x)
# Create model
model = tf.keras.Sequential([
tf.keras.layers.Dense(32, input_shape=(10,), activation=custom_activation),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# Compile model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Generate synthetic data
X_train = np.random.rand(1000, 10)
y_train = np.random.randint(0, 2, size=(1000,))
# Train model
model.fit(X_train, y_train, epochs=10, batch_size=32)
print("Neural Network Training Complete!")
Optimized Fibonacci Sequence with Memoization
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
# Compute Fibonacci numbers
for i in range(30):
print(f"Fibonacci({i}) = {fibonacci(i)}")
Palindrome Check with Case and Space Handling
import re
def is_palindrome(s):
s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
return s == s[::-1]
# Test cases
print(is_palindrome("A man, a plan, a canal: Panama")) # True
print(is_palindrome("race a car")) # False
Advanced Binary Search with Recursive Implementation
def binary_search(arr, target, low=0, high=None):
if high is None:
high = len(arr) - 1
if low > high:
return -1 # Target not found
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search(arr, target, mid + 1, high)
else:
return binary_search(arr, target, low, mid - 1)
# Example usage
arr = [2, 3, 4, 10, 40]
print("Element found at index:", binary_search(arr, 10))
Factorial Calculation Using Iterative and Recursive Methods
def factorial_recursive(n):
return 1 if n == 0 else n * factorial_recursive(n - 1)
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
# Example usage
print("Recursive:", factorial_recursive(5))
print("Iterative:", factorial_iterative(5))
Merge Sort with Performance Analysis
import time
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
sorted_array = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted_array.append(left[i])
i += 1
else:
sorted_array.append(right[j])
j += 1
sorted_array.extend(left[i:])
sorted_array.extend(right[j:])
return sorted_array
# Test and time analysis
arr = [12, 11, 13, 5, 6, 7]
start_time = time.time()
sorted_arr = merge_sort(arr)
end_time = time.time()
print("Sorted array:", sorted_arr)
print("Execution time:", end_time - start_time, "seconds")
Bubble Sort with Swap Optimization
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break # If no swaps occurred, array is already sorted
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr)
Random Password Generator with Custom Rules
import random
import string
def generate_password(length=12, use_special_chars=True):
characters = string.ascii_letters + string.digits
if use_special_chars:
characters += string.punctuation
return ''.join(random.choice(characters) for i in range(length))
# Example usage
print("Generated Password:", generate_password(16))
Prime Number Checker with Efficiency
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# Example usage
print("Is 29 prime?", is_prime(29))
Dijkstra’s Algorithm for Shortest Path
import heapq
def dijkstra(graph, start):
priority_queue = []
heapq.heappush(priority_queue, (0, start))
distances = {node: float('inf') for node in graph}
distances[start] = 0
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return distances
# Example graph representation
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
print("Shortest paths:", dijkstra(graph, 'A'))
Multithreading Example with Locks
import threading
class Counter:
def __init__(self):
self.value = 0
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.value += 1
def worker(counter):
for _ in range(100000):
counter.increment()
counter = Counter()
threads = [threading.Thread(target=worker, args=(counter,)) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print("Final counter value:", counter.value)
Web Scraper with BeautifulSoup
import requests
from bs4 import BeautifulSoup
def scrape_website(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for heading in soup.find_all('h2'):
print("Heading:", heading.text.strip())
scrape_website("https://example.com")
Chatbot with Basic NLP
import random
responses = {
"hello": ["Hello!", "Hi there!", "Hey!"],
"how are you": ["I'm just a bot, but I'm fine!", "Doing well, thanks!"],
"bye": ["Goodbye!", "See you later!", "Bye for now!"]
}
def chatbot():
print("Chatbot: Type 'exit' to end the chat.")
while True:
user_input = input("You: ").lower()
if user_input == "exit":
print("Chatbot: Goodbye!")
break
response = random.choice(responses.get(user_input, ["I don't understand."]))
print("Chatbot:", response)
chatbot()
Sudoku Solver with Backtracking
def is_valid(board, row, col, num):
for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
start_row, start_col = 3 * (row // 3), 3 * (col // 3)
for i in range(3):
for j in range(3):
if board[start_row + i][start_col + j] == num:
return False
return True
def solve_sudoku(board):
for row in range(9):
for col in range(9):
if board[row][col] == 0:
for num in range(1, 10):
if is_valid(board, row, col, num):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0
return False
return True
Graph DFS Traversal
def dfs(graph, node, visited=None):
if visited is None:
visited = set()
if node not in visited:
print(node, end=' ')
visited.add(node)
for neighbor in graph.get(node, []):
dfs(graph, neighbor, visited)
# Example graph
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
dfs(graph, 'A')
Email Sender with SMTP
import smtplib
from email.mime.text import MIMEText
def send_email(to_email, subject, body):
sender_email = "your_email@example.com"
sender_password = "your_password"
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = sender_email
msg["To"] = to_email
try:
with smtplib.SMTP_SSL("smtp.example.com", 465) as server:
server.login(sender_email, sender_password)
server.sendmail(sender_email, to_email, msg.as_string())
print("Email sent successfully!")
except Exception as e:
print("Error sending email:", e)
send_email("recipient@example.com", "Test Subject", "This is a test email.")
Matrix Multiplication
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
C = np.dot(A, B)
print("Resultant Matrix:")
print(C)
Basic Web Server with Flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to my web server!"
if __name__ == '__main__':
app.run(debug=True)
Stock Price Scraper Using Yahoo Finance API
import yfinance as yf
def get_stock_price(ticker):
stock = yf.Ticker(ticker)
return stock.history(period="1d")["Close"].iloc[-1]
print("AAPL Stock Price:", get_stock_price("AAPL"))
Weather Data Fetcher from OpenWeatherMap API
import requests
def get_weather(city):
API_KEY = "your_api_key_here"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"
response = requests.get(url).json()
return f"Weather in {city}: {response['weather'][0]['description']}, Temp: {response['main']['temp']}°C"
print(get_weather("New York"))