topic stringlengths 4 65 | language stringclasses 2
values | code stringlengths 20 791 | note stringclasses 1
value |
|---|---|---|---|
Hello World | python | print("Hello, World!") | |
Hello World | nim | echo "Hello, World!" | |
Bien so va kieu du lieu | python | x = 10
y = 3.14
name = "Python"
print(x, y, name) | |
Bien so va kieu du lieu | nim | var x: int = 10
var y: float = 3.14
var name: string = "Nim"
echo x, " ", y, " ", name | |
Vong lap for | python | for i in range(5):
print(i) | |
Vong lap for | nim | for i in 0..<5:
echo i | |
Vong lap while | python | i = 0
while i < 5:
print(i)
i += 1 | |
Vong lap while | nim | var i = 0
while i < 5:
echo i
inc i | |
Cau lenh if-else | python | x = 10
if x > 5:
print("lon hon 5")
else:
print("nho hon hoac bang 5") | |
Cau lenh if-else | nim | let x = 10
if x > 5:
echo "lon hon 5"
else:
echo "nho hon hoac bang 5" | |
Ham co ban | python | def add(a, b):
return a + b
print(add(3, 4)) | |
Ham co ban | nim | proc add(a, b: int): int =
return a + b
echo add(3, 4) | |
De quy - tinh giai thua | python | def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) | |
De quy - tinh giai thua | nim | proc factorial(n: int): int =
if n <= 1: return 1
return n * factorial(n - 1)
echo factorial(5) | |
Fibonacci | python | def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
for i in range(11):
print(fib(i)) | |
Fibonacci | nim | proc fib(n: int): int =
if n <= 1: return n
return fib(n - 1) + fib(n - 2)
for i in 0..10:
echo fib(i) | |
Danh sach (list/array) | python | arr = [1, 2, 3, 4, 5]
for x in arr:
print(x) | |
Danh sach (list/array) | nim | var arr = @[1, 2, 3, 4, 5]
for x in arr:
echo x | |
Dictionary/Table (key-value) | python | d = {"a": 1, "b": 2}
print(d["a"]) | |
Dictionary/Table (key-value) | nim | import tables
var t = {"a": 1, "b": 2}.toTable
echo t["a"] | |
Tap hop (set) | python | s = {1, 2, 3}
print(s) | |
Tap hop (set) | nim | var s = {1, 2, 3}
echo s | |
Tuple | python | t = (1, "hello")
print(t[0], t[1]) | |
Tuple | nim | let t = (1, "hello")
echo t[0], " ", t[1] | |
Thao tac chuoi (string) | python | s = "Hello, Python!"
print(s.upper())
print(len(s)) | |
Thao tac chuoi (string) | nim | import std/strutils
let s = "Hello, Nim!"
echo s.toUpperAscii()
echo s.len | |
Doc/ghi file | python | with open("test.txt", "w") as f:
f.write("Hello file\n")
with open("test.txt", "r") as f:
print(f.read()) | |
Doc/ghi file | nim | let f = open("test.txt", fmWrite)
f.writeLine("Hello file")
f.close()
let content = readFile("test.txt")
echo content | |
Xu ly loi (exception) | python | try:
raise ValueError("loi")
except ValueError as e:
print("Bat loi:", e) | |
Xu ly loi (exception) | nim | try:
raise newException(ValueError, "loi")
except ValueError as e:
echo "Bat loi: ", e.msg | |
Class/Object (OOP) | python | class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} keu")
a = Animal("Cho")
a.speak() | |
Class/Object (OOP) | nim | type
Animal = object
name: string
proc speak(a: Animal) =
echo a.name, " keu"
let a = Animal(name: "Cho")
a.speak() | |
Ke thua (inheritance) | python | class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Dong vat keu")
class Dog(Animal):
def speak(self):
print(f"{self.name} sua")
d = Dog("Rex")
d.speak() | |
Ke thua (inheritance) | nim | type
Animal = object of RootObj
name: string
Dog = object of Animal
method speak(a: Animal) {.base.} =
echo "Dong vat keu"
method speak(d: Dog) =
echo d.name, " sua"
var d = Dog(name: "Rex")
speak(d) | |
Sap xep bubble sort | python | def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
print(bubble_sort([5, 2, 8, 1, 9])) | |
Sap xep bubble sort | nim | proc bubbleSort(arr: var seq[int]) =
for i in 0..<arr.len:
for j in 0..<arr.len - i - 1:
if arr[j] > arr[j + 1]:
swap(arr[j], arr[j + 1])
var arr = @[5, 2, 8, 1, 9]
bubbleSort(arr)
echo arr | |
Sap xep quick sort | python | def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
mid = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + mid + quick_sort(right)
print(quick_sort([10, 7, 8, 9, 1, 5])) | |
Sap xep quick sort | nim | proc quickSort(arr: var seq[int], low, high: int) =
if low < high:
let pivot = arr[high]
var i = low - 1
for j in low..<high:
if arr[j] < pivot:
inc i
swap(arr[i], arr[j])
swap(arr[i + 1], arr[high])
let p = i + 1
quickSort(arr, low, p - 1)
quickSort(arr, p + 1, high)... | |
Tim kiem nhi phan (binary search) | python | 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
print(binary_search([1, 3, 5, 7, ... | |
Tim kiem nhi phan (binary search) | nim | proc binarySearch(arr: seq[int], target: int): int =
var low = 0
var high = arr.len - 1
while low <= high:
let mid = (low + high) div 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
let arr = @[1, 3, 5, 7, 9, 11]
echo bi... | |
Ham bac cao (map/filter) | python | nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
print(doubled)
print(evens) | |
Ham bac cao (map/filter) | nim | import std/sequtils
let nums = @[1, 2, 3, 4, 5]
let doubled = nums.map(proc(x: int): int = x * 2)
let evens = nums.filter(proc(x: int): bool = x mod 2 == 0)
echo doubled
echo evens | |
List/seq comprehension | python | squares = [x * x for x in range(1, 6)]
print(squares) | |
List/seq comprehension | nim | import std/sugar
let squares = collect(newSeq):
for x in 1..5:
x * x
echo squares | |
Ham lambda | python | add = lambda a, b: a + b
print(add(3, 4)) | |
Ham lambda | nim | let add = proc(a, b: int): int = a + b
echo add(3, 4) | |
Module/import co ban | python | import math
print(math.sqrt(16))
print(math.pow(2, 10)) | |
Module/import co ban | nim | import std/math
echo sqrt(16.0)
echo pow(2.0, 10.0) | |
Kiem tra so nguyen to | python | def is_prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
for i in range(2, 21):
if is_prime(i):
print(i) | |
Kiem tra so nguyen to | nim | proc isPrime(n: int): bool =
if n < 2: return false
for i in 2..<n:
if n mod i == 0:
return false
return true
for i in 2..20:
if isPrime(i):
echo i | |
Tinh UCLN (GCD) | python | def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(48, 18)) | |
Tinh UCLN (GCD) | nim | proc gcd(a, b: int): int =
var a = a
var b = b
while b != 0:
let t = b
b = a mod b
a = t
return a
echo gcd(48, 18) | |
Doi cho hai bien (swap) | python | a, b = 5, 10
a, b = b, a
print(a, b) | |
Doi cho hai bien (swap) | nim | var a = 5
var b = 10
swap(a, b)
echo a, " ", b | |
Doc du lieu tu ban phim | python | name = input("Nhap ten cua ban: ")
print(f"Xin chao, {name}!") | |
Doc du lieu tu ban phim | nim | stdout.write("Nhap ten cua ban: ")
let name = readLine(stdin)
echo "Xin chao, ", name, "!" | |
Xu ly nhieu loai ngoai le | python | try:
x = int("abc")
except ValueError:
print("Khong the chuyen doi chuoi thanh so")
finally:
print("Ket thuc xu ly") | |
Xu ly nhieu loai ngoai le | nim | try:
let x = parseInt("abc")
except ValueError:
echo "Khong the chuyen doi chuoi thanh so"
finally:
echo "Ket thuc xu ly" | |
Doc file theo tung dong | python | with open("test.txt", "r") as f:
for line in f:
print(line.strip()) | |
Doc file theo tung dong | nim | for line in lines("test.txt"):
echo line | |
Ngan xep (Stack) | python | stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack.pop())
print(stack) | |
Ngan xep (Stack) | nim | var stack: seq[int] = @[]
stack.add(1)
stack.add(2)
stack.add(3)
echo stack.pop()
echo stack | |
Hang doi (Queue) | python | from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
queue.append(3)
print(queue.popleft())
print(queue) | |
Hang doi (Queue) | nim | import std/deques
var queue = initDeque[int]()
queue.addLast(1)
queue.addLast(2)
queue.addLast(3)
echo queue.popFirst()
echo queue | |
Danh sach lien ket don (Singly Linked List) | python | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
node = Node(value)
if not self.head:
self.head = node
return
cur = self.head
... | |
Danh sach lien ket don (Singly Linked List) | nim | type
Node = ref object
value: int
next: Node
LinkedList = ref object
head: Node
proc append(l: LinkedList, value: int) =
let node = Node(value: value)
if l.head == nil:
l.head = node
return
var cur = l.head
while cur.next != nil:
cur = cur.next
cur.next = node
proc printList(l: ... | |
Cay nhi phan tim kiem (BST) - chen node | python | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, value):
if root is None:
return Node(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, val... | |
Cay nhi phan tim kiem (BST) - chen node | nim | type
Node = ref object
value: int
left, right: Node
proc insert(root: Node, value: int): Node =
if root == nil:
return Node(value: value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
var root: Node = nil
for v in [5,... | |
Duyet cay theo thu tu (Inorder traversal) | python | def inorder(root, result):
if root is None:
return
inorder(root.left, result)
result.append(root.value)
inorder(root.right, result)
return result
result = inorder(root, [])
print(result) | |
Duyet cay theo thu tu (Inorder traversal) | nim | proc inorder(root: Node, res: var seq[int]) =
if root == nil:
return
inorder(root.left, res)
res.add(root.value)
inorder(root.right, res)
var res: seq[int] = @[]
inorder(root, res)
echo res | |
BFS tren do thi (Breadth-First Search) | python | from collections import deque
def bfs(graph, start):
visited = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
... | |
BFS tren do thi (Breadth-First Search) | nim | import std/[tables, sets, deques]
proc bfs(graph: Table[int, seq[int]], start: int): seq[int] =
var visited = initHashSet[int]()
visited.incl(start)
var queue = initDeque[int]()
queue.addLast(start)
var order: seq[int] = @[]
while queue.len > 0:
let node = queue.popFirst()
order.add(node)
for n... | |
DFS tren do thi (Depth-First Search) | python | def dfs(graph, start, visited=None, order=None):
if visited is None:
visited = set()
order = []
visited.add(start)
order.append(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited, order)
return order
graph = {1: [2, 3], ... | |
DFS tren do thi (Depth-First Search) | nim | import std/[tables, sets]
proc dfs(graph: Table[int, seq[int]], start: int, visited: var HashSet[int], order: var seq[int]) =
visited.incl(start)
order.add(start)
for neighbor in graph[start]:
if neighbor notin visited:
dfs(graph, neighbor, visited, order)
let graph = {1: @[2, 3], 2: @[4], 3: @[4], 4:... | |
Bang bam (Hash Table) tu cai dat don gian | python | class HashTable:
def __init__(self, size=10):
self.size = size
self.buckets = [[] for _ in range(size)]
def _hash(self, key):
return sum(ord(c) for c in key) % self.size
def set(self, key, value):
idx = self._hash(key)
for pair in self.buckets[idx]:
if p... | |
Bang bam (Hash Table) tu cai dat don gian | nim | type
HashTable = object
buckets: seq[seq[(string, string)]]
size: int
proc newHashTable(size: int = 10): HashTable =
result.size = size
result.buckets = newSeq[seq[(string, string)]](size)
proc hashKey(key: string, size: int): int =
var s = 0
for c in key:
s += ord(c)
return s mod size
proc s... | |
Kiem tra chuoi doi xung (Palindrome) | python | def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome("madam"))
print(is_palindrome("hello")) | |
Kiem tra chuoi doi xung (Palindrome) | nim | import std/strutils
proc isPalindrome(s: string): bool =
let clean = s.toLowerAscii().replace(" ", "")
return clean == clean.reversed()
echo isPalindrome("madam")
echo isPalindrome("hello") | |
Kiem tra anagram | python | def is_anagram(a, b):
return sorted(a) == sorted(b)
print(is_anagram("listen", "silent"))
print(is_anagram("hello", "world")) | |
Kiem tra anagram | nim | import std/algorithm
proc isAnagram(a, b: string): bool =
var x = a
var y = b
x.sort()
y.sort()
return x == y
echo isAnagram("listen", "silent")
echo isAnagram("hello", "world") | |
Dao nguoc chuoi | python | s = "Hello, Python!"
print(s[::-1]) | |
Dao nguoc chuoi | nim | import std/algorithm
var s = "Hello, Nim!"
echo s.reversed() | |
Dem tan so tu trong chuoi | python | from collections import Counter
s = "con meo con cho con ga"
words = s.split()
counter = Counter(words)
print(counter) | |
Dem tan so tu trong chuoi | nim | import std/[tables, strutils]
let s = "con meo con cho con ga"
let words = s.split(" ")
var counter = initCountTable[string]()
for w in words:
counter.inc(w)
echo counter | |
Sap xep chen (Insertion sort) | python | def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
print(insertion_sort([9, 5, 1, 4, 3])) | |
Sap xep chen (Insertion sort) | nim | proc insertionSort(arr: var seq[int]) =
for i in 1..<arr.len:
let key = arr[i]
var j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
dec j
arr[j + 1] = key
var arr = @[9, 5, 1, 4, 3]
insertionSort(arr)
echo arr | |
Sap xep chon (Selection sort) | python | def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
print(selection_sort([64, 25, 12, 22, 11])) | |
Sap xep chon (Selection sort) | nim | proc selectionSort(arr: var seq[int]) =
let n = arr.len
for i in 0..<n:
var minIdx = i
for j in i + 1..<n:
if arr[j] < arr[minIdx]:
minIdx = j
swap(arr[i], arr[minIdx])
var arr = @[64, 25, 12, 22, 11]
selectionSort(arr)
echo arr | |
Sap xep tron (Merge sort) | python | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i]); i += 1
else:
... | |
Sap xep tron (Merge sort) | nim | proc mergeSort(arr: seq[int]): seq[int] =
if arr.len <= 1:
return arr
let mid = arr.len div 2
let left = mergeSort(arr[0..<mid])
let right = mergeSort(arr[mid..^1])
var res: seq[int] = @[]
var i = 0
var j = 0
while i < left.len and j < right.len:
if left[i] < right[j]:
res.add(left[i]); in... | |
Tim kiem tuyen tinh (Linear search) | python | def linear_search(arr, target):
for i, v in enumerate(arr):
if v == target:
return i
return -1
print(linear_search([4, 2, 7, 1, 9], 7)) | |
Tim kiem tuyen tinh (Linear search) | nim | proc linearSearch(arr: seq[int], target: int): int =
for i, v in arr:
if v == target:
return i
return -1
echo linearSearch(@[4, 2, 7, 1, 9], 7) | |
Tim gia tri lon nhat/nho nhat trong mang | python | arr = [4, 2, 7, 1, 9]
print(max(arr), min(arr)) | |
Tim gia tri lon nhat/nho nhat trong mang | nim | import std/[algorithm, sequtils]
let arr = @[4, 2, 7, 1, 9]
echo max(arr), " ", min(arr) | |
Tong cac phan tu trong mang | python | arr = [1, 2, 3, 4, 5]
print(sum(arr)) | |
Tong cac phan tu trong mang | nim | import std/sequtils
let arr = @[1, 2, 3, 4, 5]
echo arr.foldl(a + b) | |
Dao nguoc mang | python | arr = [1, 2, 3, 4, 5]
print(arr[::-1]) | |
Dao nguoc mang | nim | import std/algorithm
var arr = @[1, 2, 3, 4, 5]
echo arr.reversed() | |
Xoay mang (rotate array) | python | def rotate(arr, k):
n = len(arr)
k = k % n
return arr[-k:] + arr[:-k]
print(rotate([1, 2, 3, 4, 5], 2)) | |
Xoay mang (rotate array) | nim | proc rotate(arr: seq[int], k: int): seq[int] =
let n = arr.len
let kk = k mod n
return arr[n - kk..^1] & arr[0..<n - kk]
echo rotate(@[1, 2, 3, 4, 5], 2) |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 17