Algorithms are the backbone of modern technology. but what is an algorithm?
Algorithm
al·go·rithm /ˈalɡəˌriT͟Həm/
noun
plural: algorithms
Definition:
A process or set of rules to be followed in calculations or other problem-solving operations, especially by a computer.
Example sentence:
“a basic algorithm for division”
Origin:
Late Middle English: from French algorisme, from medieval Latin algorismus, from the name of the mathematician al-Khwārizmī (9th century), who introduced Arabic numerals.
Oxford Languages Dictionary
An algorithm is a sequence of instructions to follow to get a specified outcome.
For Example:
Making a sandwich
This is a simple algorithm for making a sandwich. Algorithms can be much more complex, especially in computer science where they can involve sorting data, searching for information, or performing calculations.
scroll down for algorithm demos and examples
Binary search is an efficient algorithm for finding an item in a sorted list of items.
Binary search works like finding a word in a dictionary:
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Quick sort is a divide-and-conquer sorting algorithm that works by selecting a pivot element and partitioning the array around it.
Quick sort is like sorting cards:
def quicksort(arr):
if len(arr) <= 1:
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]
return quicksort(left) + middle + quicksort(right)
Depth-First Search (DFS) is an algorithm for pathfinding, traversing or searching tree or graph data structures.
Depth-First Search explores like exploring a cave:
def dfs(graph, node, visited=None):
if visited is None:
visited = set()
if node not in visited:
print(node)
visited.add(node)
for neighbor in graph[node]:
dfs(graph, neighbor, visited)
return visited
# Example Graph
# graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []}
No file chosen
ASCII art turns pictures into text:
from PIL import Image
def image_to_ascii(image, width=100):
ascii_chars = "@%#*+=-:. "
aspect_ratio = image.height / image.width
new_height = int(aspect_ratio * width * 0.55)
img_resized = image.resize((width, new_height))
img_gray = img_resized.convert("L")
pixels = img_gray.getdata()
ascii_str = "".join(ascii_chars[pixel * len(ascii_chars) // 256] for pixel in pixels)
ascii_rows = [ascii_str[i:i+width] for i in range(0, len(ascii_str), width)]
return ascii_rows
click on any "video" to initialize the algorithm
Social media algorithm learns what you like:
import random
# 1. SETUP: The Metadata
CATEGORIES = ["Tech", "Gaming", "Music", "Food", "Travel"]
TAGS = ["Lofi", "Tutorial", "Hardware", "Review", "Live", "Budget", "AI", "Retro"]
# 2. STATE: The "User Profile" (Initial interest is equal)
category_weights = {cat: 1.0 for cat in CATEGORIES}
tag_weights = {tag: 1.0 for tag in TAGS}
def generate_random_video():
"""Simulates a video being uploaded to the platform."""
cat = random.choice(CATEGORIES)
# Pick 2 random tags
v_tags = random.sample(TAGS, 2)
return {
"title": f"{cat} Video {random.randint(100, 999)}",
"category": cat,
"tags": v_tags
}
def get_algorithm_score(video):
"""The Core Algorithm: Multi-factor ranking."""
c_score = category_weights[video["category"]]
t_score = sum(tag_weights[tag] for tag in video["tags"])
return (c_score * 1.5) + t_score # Categories slightly more important
def display_feed(limit=3):
"""Generates a large pool but only shows the 'Recommended' top results."""
pool = [generate_random_video() for _ in range(20)]
# Sort the pool using our algorithm
recommended = sorted(pool, key=get_algorithm_score, reverse=True)
print("\n--- YOUR RECOMMENDED FEED ---")
for i, v in enumerate(recommended[:limit]):
print(f"{i+1}. {v['title']} | Category: {v['category']} | Tags: {v['tags']}")
print("------------------------------")
def simulate_click(category, tags):
"""Update weights based on user engagement."""
category_weights[category] += 2.0
for t in tags:
tag_weights[t] += 1.5
# Simulation of 'Interest Decay' (others lose priority over time)
for c in category_weights:
category_weights[c] *= 0.95
for t in tag_weights:
tag_weights[t] *= 0.95
# --- EXECUTION SIMULATION ---
# Step 1: Show initial random feed
print("SYSTEM: New user detected. Showing baseline content.")
display_feed()
# Step 2: User clicks a 'Tech' video with '#Hardware'
print("\n[USER CLICK]: Tech Video with #Hardware and #Review")
simulate_click("Tech", ["Hardware", "Review"])
# Step 3: Show feed again.
# It will now prioritize Tech, but also anything with Hardware/Review tags!
print("\nSYSTEM: Recalculating weights...")
display_feed()
# Step 4: User clicks a 'Gaming' video with '#Hardware'
# This is the 'Cross-over' - the user likes Hardware regardless of the category.
print("\n[USER CLICK]: Gaming Video with #Hardware and #Retro")
simulate_click("Gaming", ["Hardware", "Retro"])
print("\nSYSTEM: Final Result (Algorithm now understands you like #Hardware everywhere)")
display_feed()