topic
stringlengths
4
65
language
stringclasses
2 values
code
stringlengths
20
791
note
stringclasses
1 value
Abstract class / interface
python
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 s = Square(4) print(s.area())
Abstract class / interface
nim
type Shape = ref object of RootObj method area(s: Shape): float {.base.} = raise newException(CatchableError, "Chua duoc cai dat") type Square = ref object of Shape side: float method area(s: Square): float = return s.side * s.side let s = Square(side: 4.0) echo s.area()
Mixin
python
class SerializableMixin: def to_dict(self): return self.__dict__ class User(SerializableMixin): def __init__(self, name, age): self.name = name self.age = age u = User("An", 25) print(u.to_dict())
Mixin (dung concept + template)
nim
type User = object name: string age: int proc toDict(u: User): string = return "{name: " & u.name & ", age: " & $u.age & "}" let u = User(name: "An", age: 25) echo u.toDict()
Memoization / caching (lru_cache)
python
from functools import lru_cache @lru_cache(maxsize=None) def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2) print(fib(30))
Memoization / caching tu cai dat
nim
import std/tables var cache = initTable[int, int]() proc fib(n: int): int = if n <= 1: return n if cache.hasKey(n): return cache[n] let result = fib(n - 1) + fib(n - 2) cache[n] = result return result echo fib(30)
Generator expression
python
nums = (x * x for x in range(10)) print(sum(nums))
Iterator (tuong duong generator expression)
nim
iterator squares(n: int): int = for x in 0..<n: yield x * x var total = 0 for s in squares(10): total += s echo total
Context manager voi contextlib
python
from contextlib import contextmanager @contextmanager def timer(): print("Bat dau") yield print("Ket thuc") with timer(): print("Dang xu ly...")
Template lam context manager
nim
template timer(body: untyped) = echo "Bat dau" body echo "Ket thuc" timer: echo "Dang xu ly..."
Threading Lock / Mutex
python
import threading lock = threading.Lock() counter = 0 def increment(): global counter with lock: counter += 1 threads = [threading.Thread(target=increment) for _ in range(10)] for t in threads: t.start() for t in threads: t.join() print(counter)
Threading Lock / Mutex
nim
import std/locks var lock: Lock var counter = 0 initLock(lock) proc increment() {.thread.} = acquire(lock) inc counter release(lock) var threads: array[10, Thread[void]] for i in 0..<10: createThread(threads[i], increment) joinThreads(threads) echo counter
Queue giao tiep giua threads
python
import queue import threading q = queue.Queue() def producer(): for i in range(5): q.put(i) t = threading.Thread(target=producer) t.start() t.join() while not q.empty(): print(q.get())
Channel giao tiep giua threads
nim
import std/[os, locks] var chan: Channel[int] chan.open() proc producer() {.thread.} = for i in 0..<5: chan.send(i) var t: Thread[void] createThread(t, producer) joinThread(t) for i in 0..<5: echo chan.recv()
Socket TCP client don gian
python
import socket def send_message(host, port, msg): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((host, port)) s.sendall(msg.encode()) data = s.recv(1024) return data.decode() # print(send_message("localhost", 8080, "hello"))
Socket TCP client don gian
nim
import std/net proc sendMessage(host: string, port: int, msg: string): string = var socket = newSocket() socket.connect(host, Port(port)) socket.send(msg) let data = socket.recvLine() socket.close() return data # echo sendMessage("localhost", 8080, "hello")
Regex nang cao (groups, replace)
python
import re text = "Ngay: 28/07/2026" match = re.search(r"(\d+)/(\d+)/(\d+)", text) if match: print(match.group(1), match.group(2), match.group(3)) replaced = re.sub(r"\d+", "X", text) print(replaced)
Regex nang cao (groups, replace)
nim
import std/re let text = "Ngay: 28/07/2026" var matches: array[3, string] if text.match(re"(\d+)/(\d+)/(\d+)", matches): echo matches[0], " ", matches[1], " ", matches[2] let replaced = text.replace(re"\d+", "X") echo replaced
Cay nhi phan - tim kiem gia tri
python
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def search(root, value): if root is None: return False if root.value == value: return True if value < root.value: return search(root.left, value) return searc...
Cay nhi phan - tim kiem gia tri
nim
type Node = ref object value: int left, right: Node proc search(root: Node, value: int): bool = if root == nil: return false if root.value == value: return true if value < root.value: return search(root.left, value) return search(root.right, value)
Cay nhi phan - tinh chieu cao
python
def height(root): if root is None: return 0 return 1 + max(height(root.left), height(root.right))
Cay nhi phan - tinh chieu cao
nim
proc height(root: Node): int = if root == nil: return 0 return 1 + max(height(root.left), height(root.right))
Heap / hang doi uu tien (priority queue)
python
import heapq heap = [] heapq.heappush(heap, 5) heapq.heappush(heap, 1) heapq.heappush(heap, 3) print(heapq.heappop(heap)) print(heap)
Heap / hang doi uu tien (priority queue)
nim
import std/heapqueue var heap = initHeapQueue[int]() heap.push(5) heap.push(1) heap.push(3) echo heap.pop()
Trie (cay tien to)
python
class TrieNode: def __init__(self): self.children = {} self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for c in word: if c not in node.children: node.children[c] = TrieNo...
Trie (cay tien to)
nim
import std/tables type TrieNode = ref object children: Table[char, TrieNode] isEnd: bool Trie = ref object root: TrieNode proc newTrie(): Trie = Trie(root: TrieNode(children: initTable[char, TrieNode]())) proc insert(t: Trie, word: string) = var node = t.root for c in word: if c notin node...
Union-Find (Disjoint Set)
python
class UnionFind: def __init__(self, n): self.parent = list(range(n)) def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): rx, ry = self.find(x), self.find(y) if rx != ry: ...
Union-Find (Disjoint Set)
nim
type UnionFind = object parent: seq[int] proc newUnionFind(n: int): UnionFind = result.parent = newSeq[int](n) for i in 0..<n: result.parent[i] = i proc find(uf: var UnionFind, x: int): int = if uf.parent[x] != x: uf.parent[x] = uf.find(uf.parent[x]) return uf.parent[x] proc union(uf: var Union...
Dynamic Programming - bai toan cai tui (knapsack)
python
def knapsack(weights, values, capacity): n = len(weights) dp = [[0] * (capacity + 1) for _ in range(n + 1)] for i in range(1, n + 1): for w in range(capacity + 1): if weights[i - 1] <= w: dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]) ...
Dynamic Programming - bai toan cai tui (knapsack)
nim
proc knapsack(weights, values: seq[int], capacity: int): int = let n = weights.len var dp = newSeqWith(n + 1, newSeq[int](capacity + 1)) for i in 1..n: for w in 0..capacity: if weights[i - 1] <= w: dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]) else: dp...
Dynamic Programming - day con chung dai nhat (LCS)
python
def lcs(a, b): m, n = len(a), len(b) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if a[i - 1] == b[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) re...
Dynamic Programming - day con chung dai nhat (LCS)
nim
import std/sequtils proc lcs(a, b: string): int = let m = a.len let n = b.len var dp = newSeqWith(m + 1, newSeq[int](n + 1)) for i in 1..m: for j in 1..n: if a[i - 1] == b[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[m][n] ...
Thuat toan Dijkstra tim duong di ngan nhat
python
import heapq def dijkstra(graph, start): dist = {node: float("inf") for node in graph} dist[start] = 0 pq = [(0, start)] while pq: d, node = heapq.heappop(pq) if d > dist[node]: continue for neighbor, weight in graph[node]: new_dist = d + weight ...
Thuat toan Dijkstra tim duong di ngan nhat
nim
import std/[tables, heapqueue] proc dijkstra(graph: Table[string, seq[(string, int)]], start: string): Table[string, int] = var dist = initTable[string, int]() for node in graph.keys: dist[node] = high(int) dist[start] = 0 var pq = initHeapQueue[(int, string)]() pq.push((0, start)) while pq.len > 0: ...
Sap xep topo (topological sort)
python
from collections import deque def topo_sort(graph): in_degree = {node: 0 for node in graph} for node in graph: for neighbor in graph[node]: in_degree[neighbor] += 1 queue = deque([n for n in in_degree if in_degree[n] == 0]) order = [] while queue: node = queue.popleft() ...
Sap xep topo (topological sort)
nim
import std/[tables, deques] proc topoSort(graph: Table[string, seq[string]]): seq[string] = var inDegree = initTable[string, int]() for node in graph.keys: inDegree[node] = 0 for node in graph.keys: for neighbor in graph[node]: inDegree[neighbor] += 1 var queue = initDeque[string]() for node, d...
Sliding window - tong lon nhat cua doan con
python
def max_sum_subarray(arr, k): max_sum = sum(arr[:k]) window_sum = max_sum for i in range(k, len(arr)): window_sum += arr[i] - arr[i - k] max_sum = max(max_sum, window_sum) return max_sum print(max_sum_subarray([1, 4, 2, 10, 2, 3, 1, 0, 20], 4))
Sliding window - tong lon nhat cua doan con
nim
import std/sequtils proc maxSumSubarray(arr: seq[int], k: int): int = var maxSum = arr[0..<k].foldl(a + b) var windowSum = maxSum for i in k..<arr.len: windowSum += arr[i] - arr[i - k] maxSum = max(maxSum, windowSum) return maxSum echo maxSumSubarray(@[1, 4, 2, 10, 2, 3, 1, 0, 20], 4)
Two pointers - loai bo phan tu trung lap trong mang da sap xep
python
def remove_duplicates(arr): if not arr: return 0 slow = 0 for fast in range(1, len(arr)): if arr[fast] != arr[slow]: slow += 1 arr[slow] = arr[fast] return slow + 1 arr = [1, 1, 2, 2, 3, 4, 4] print(remove_duplicates(arr))
Two pointers - loai bo phan tu trung lap trong mang da sap xep
nim
proc removeDuplicates(arr: var seq[int]): int = if arr.len == 0: return 0 var slow = 0 for fast in 1..<arr.len: if arr[fast] != arr[slow]: inc slow arr[slow] = arr[fast] return slow + 1 var arr = @[1, 1, 2, 2, 3, 4, 4] echo removeDuplicates(arr)
Bit manipulation - dem so bit 1
python
def count_set_bits(n): count = 0 while n: count += n & 1 n >>= 1 return count print(count_set_bits(29))
Bit manipulation - dem so bit 1
nim
proc countSetBits(n: int): int = var n = n var count = 0 while n > 0: count += n and 1 n = n shr 1 return count echo countSetBits(29)
Bit manipulation - XOR swap hai bien
python
a, b = 5, 10 a ^= b b ^= a a ^= b print(a, b)
Bit manipulation - XOR swap hai bien
nim
var a = 5 var b = 10 a = a xor b b = a xor b a = a xor b echo a, " ", b
De quy - Thap Hanoi (Tower of Hanoi)
python
def hanoi(n, source, target, aux): if n == 1: print(f"Di chuyen dia 1 tu {source} sang {target}") return hanoi(n - 1, source, aux, target) print(f"Di chuyen dia {n} tu {source} sang {target}") hanoi(n - 1, aux, target, source) hanoi(3, "A", "C", "B")
De quy - Thap Hanoi (Tower of Hanoi)
nim
proc hanoi(n: int, source, target, aux: string) = if n == 1: echo "Di chuyen dia 1 tu ", source, " sang ", target return hanoi(n - 1, source, aux, target) echo "Di chuyen dia ", n, " tu ", source, " sang ", target hanoi(n - 1, aux, target, source) hanoi(3, "A", "C", "B")
Fibonacci voi Dynamic Programming (bottom-up)
python
def fib_dp(n): if n <= 1: return n dp = [0] * (n + 1) dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] print(fib_dp(30))
Fibonacci voi Dynamic Programming (bottom-up)
nim
proc fibDp(n: int): int = if n <= 1: return n var dp = newSeq[int](n + 1) dp[1] = 1 for i in 2..n: dp[i] = dp[i - 1] + dp[i - 2] return dp[n] echo fibDp(30)
Tim kiem chuoi con (naive string matching)
python
def find_substring(text, pattern): n, m = len(text), len(pattern) positions = [] for i in range(n - m + 1): if text[i:i + m] == pattern: positions.append(i) return positions print(find_substring("ababcababc", "abc"))
Tim kiem chuoi con (naive string matching)
nim
proc findSubstring(text, pattern: string): seq[int] = let n = text.len let m = pattern.len var positions: seq[int] = @[] for i in 0..n - m: if text[i..<i + m] == pattern: positions.add(i) return positions echo findSubstring("ababcababc", "abc")
Doc cau hinh tu file .env
python
def load_env(path): config = {} with open(path) as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: key, value = line.split("=", 1) config[key] = value return config # config = load_env(".env")
Doc cau hinh tu file .env
nim
import std/[strutils, tables] proc loadEnv(path: string): Table[string, string] = var config = initTable[string, string]() for line in lines(path): let l = line.strip() if l.len > 0 and not l.startsWith("#") and l.contains("="): let parts = l.split("=", 1) config[parts[0]] = parts[1] return c...
Design pattern Command
python
class Command: def execute(self): pass class PrintCommand(Command): def __init__(self, msg): self.msg = msg def execute(self): print(self.msg) commands = [PrintCommand("Xin chao"), PrintCommand("Tam biet")] for cmd in commands: cmd.execute()
Design pattern Command
nim
type Command = ref object of RootObj method execute(c: Command) {.base.} = discard type PrintCommand = ref object of Command msg: string method execute(c: PrintCommand) = echo c.msg let commands = @[PrintCommand(msg: "Xin chao"), PrintCommand(msg: "Tam biet")] for cmd in commands: cmd.execute()
Design pattern Builder
python
class Pizza: def __init__(self): self.toppings = [] def add_topping(self, topping): self.toppings.append(topping) return self def __repr__(self): return f"Pizza voi {self.toppings}" pizza = Pizza().add_topping("pho mai").add_topping("nam") print(pizza)
Design pattern Builder
nim
type Pizza = ref object toppings: seq[string] proc addTopping(p: Pizza, topping: string): Pizza = p.toppings.add(topping) return p proc `$`(p: Pizza): string = "Pizza voi " & $p.toppings var pizza = Pizza(toppings: @[]) discard pizza.addTopping("pho mai").addTopping("nam") echo pizza
Kiem tra du lieu dau vao (validate input)
python
def validate_user(data): errors = [] if "name" not in data or not data["name"]: errors.append("Thieu ten") if "age" not in data or data["age"] < 0: errors.append("Tuoi khong hop le") return errors print(validate_user({"name": "", "age": -1}))
Kiem tra du lieu dau vao (validate input)
nim
import std/tables proc validateUser(data: Table[string, string]): seq[string] = var errors: seq[string] = @[] if not data.hasKey("name") or data["name"].len == 0: errors.add("Thieu ten") if not data.hasKey("age") or parseInt(data.getOrDefault("age", "-1")) < 0: errors.add("Tuoi khong hop le") return er...
Rate limiter don gian
python
import time class RateLimiter: def __init__(self, max_calls, period): self.max_calls = max_calls self.period = period self.calls = [] def allow(self): now = time.time() self.calls = [c for c in self.calls if now - c < self.period] if len(self.calls) < self.max_c...
Rate limiter don gian
nim
import std/[times, deques] type RateLimiter = object maxCalls: int period: float calls: Deque[float] proc allow(rl: var RateLimiter): bool = let now = epochTime() while rl.calls.len > 0 and now - rl.calls[0] >= rl.period: discard rl.calls.popFirst() if rl.calls.len < rl.maxCalls: rl.calls....
LRU Cache tu cai dat
python
from collections import OrderedDict class LRUCache: def __init__(self, capacity): self.capacity = capacity self.cache = OrderedDict() def get(self, key): if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self...
LRU Cache tu cai dat
nim
import std/tables type LRUCache = object capacity: int cache: OrderedTable[int, string] proc get(lru: var LRUCache, key: int): string = if not lru.cache.hasKey(key): return "-1" let value = lru.cache[key] lru.cache.del(key) lru.cache[key] = value return value proc put(lru: var LRUCache, key: ...
Retry logic voi backoff
python
import time def retry(func, max_attempts=3, delay=1): for attempt in range(max_attempts): try: return func() except Exception as e: print(f"Loi lan {attempt + 1}: {e}") time.sleep(delay * (attempt + 1)) raise Exception("Da het so lan thu lai") def risky(): ...
Retry logic voi backoff
nim
import std/os proc retry(fn: proc(), maxAttempts: int = 3, delay: int = 1) = for attempt in 0..<maxAttempts: try: fn() return except CatchableError as e: echo "Loi lan ", attempt + 1, ": ", e.msg sleep(delay * (attempt + 1) * 1000) raise newException(CatchableError, "Da het so lan t...
Currying nang cao
python
def curry_add(a): def inner(b): def inner2(c): return a + b + c return inner2 return inner print(curry_add(1)(2)(3))
Currying nang cao
nim
proc curryAdd(a: int): proc(b: int): proc(c: int): int = return proc(b: int): proc(c: int): int = return proc(c: int): int = return a + b + c echo curryAdd(1)(2)(3)
Functional pipeline (compose functions)
python
def compose(*functions): def composed(x): for fn in functions: x = fn(x) return x return composed pipeline = compose(lambda x: x + 1, lambda x: x * 2, lambda x: x - 3) print(pipeline(5))
Functional pipeline (compose functions)
nim
proc compose(fns: seq[proc(x: int): int]): proc(x: int): int = return proc(x: int): int = var result = x for fn in fns: result = fn(result) return result let pipeline = compose(@[ proc(x: int): int = x + 1, proc(x: int): int = x * 2, proc(x: int): int = x - 3 ]) echo pipeline(5)
Async HTTP - goi nhieu request dong thoi
python
import asyncio async def fetch(url): await asyncio.sleep(0.5) return f"Da tai xong {url}" async def main(): urls = ["url1", "url2", "url3"] results = await asyncio.gather(*[fetch(u) for u in urls]) print(results) asyncio.run(main())
Async HTTP - goi nhieu request dong thoi
nim
import std/asyncdispatch proc fetch(url: string): Future[string] {.async.} = await sleepAsync(500) return "Da tai xong " & url proc main() {.async.} = let urls = @["url1", "url2", "url3"] var futures: seq[Future[string]] = @[] for u in urls: futures.add(fetch(u)) let results = await all(futures) ech...
Unit test voi mock
python
from unittest.mock import MagicMock def send_email(mailer, to, msg): mailer.send(to, msg) return True mock_mailer = MagicMock() result = send_email(mock_mailer, "test@example.com", "Xin chao") mock_mailer.send.assert_called_with("test@example.com", "Xin chao") print(result)
Unit test co ban (Nim khong co mock built-in, dung stub thay the)
nim
type Mailer = object calls: seq[(string, string)] proc send(m: var Mailer, to, msg: string) = m.calls.add((to, msg)) proc sendEmail(m: var Mailer, to, msg: string): bool = m.send(to, msg) return true var mailer = Mailer(calls: @[]) let result = sendEmail(mailer, "test@example.com", "Xin chao") echo maile...
Producer-Consumer pattern
python
import queue import threading q = queue.Queue(maxsize=5) def producer(): for i in range(5): q.put(i) print(f"San xuat: {i}") def consumer(): for _ in range(5): item = q.get() print(f"Tieu thu: {item}") t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consum...
Producer-Consumer pattern
nim
import std/os var chan: Channel[int] chan.open(5) proc producer() {.thread.} = for i in 0..<5: chan.send(i) echo "San xuat: ", i proc consumer() {.thread.} = for i in 0..<5: let item = chan.recv() echo "Tieu thu: ", item var t1, t2: Thread[void] createThread(t1, producer) createThread(t2, consum...
Design pattern Chain of Responsibility
python
class Handler: def __init__(self, next_handler=None): self.next_handler = next_handler def handle(self, request): if self.next_handler: return self.next_handler.handle(request) return "Khong xu ly duoc" class AuthHandler(Handler): def handle(self, request): if r...
Design pattern Chain of Responsibility
nim
type Handler = ref object of RootObj next: Handler method handle(h: Handler, authenticated: bool): string {.base.} = if h.next != nil: return h.next.handle(authenticated) return "Khong xu ly duoc" type AuthHandler = ref object of Handler method handle(h: AuthHandler, authenticated: bool): string = ...
State machine (may trang thai)
python
class TrafficLight: def __init__(self): self.state = "red" def next_state(self): transitions = {"red": "green", "green": "yellow", "yellow": "red"} self.state = transitions[self.state] return self.state light = TrafficLight() for _ in range(4): print(light.next_state())
State machine (may trang thai)
nim
type LightState = enum Red, Green, Yellow type TrafficLight = object state: LightState proc nextState(t: var TrafficLight): LightState = case t.state of Red: t.state = Green of Green: t.state = Yellow of Yellow: t.state = Red return t.state var light = TrafficLight(state: Red) for i in 0..<4: ...
Pub/Sub (event-driven) don gian
python
class EventBus: def __init__(self): self.subscribers = {} def subscribe(self, event, fn): self.subscribers.setdefault(event, []).append(fn) def publish(self, event, data): for fn in self.subscribers.get(event, []): fn(data) bus = EventBus() bus.subscribe("user_created"...
Pub/Sub (event-driven) don gian
nim
import std/tables type EventBus = object subscribers: Table[string, seq[proc(data: string)]] proc subscribe(bus: var EventBus, event: string, fn: proc(data: string)) = if not bus.subscribers.hasKey(event): bus.subscribers[event] = @[] bus.subscribers[event].add(fn) proc publish(bus: EventBus, event: st...