mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 04:31:55 +08:00
translation: Add Python and Java code for EN version (#1345)
* Add the intial translation of code of all the languages * test * revert * Remove * Add Python and Java code for EN version
This commit is contained in:
@ -0,0 +1,65 @@
|
||||
"""
|
||||
File: iteration.py
|
||||
Created Time: 2023-08-24
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def for_loop(n: int) -> int:
|
||||
"""for loop"""
|
||||
res = 0
|
||||
# Loop sum 1, 2, ..., n-1, n
|
||||
for i in range(1, n + 1):
|
||||
res += i
|
||||
return res
|
||||
|
||||
|
||||
def while_loop(n: int) -> int:
|
||||
"""while loop"""
|
||||
res = 0
|
||||
i = 1 # Initialize condition variable
|
||||
# Loop sum 1, 2, ..., n-1, n
|
||||
while i <= n:
|
||||
res += i
|
||||
i += 1 # Update condition variable
|
||||
return res
|
||||
|
||||
|
||||
def while_loop_ii(n: int) -> int:
|
||||
"""while loop (two updates)"""
|
||||
res = 0
|
||||
i = 1 # Initialize condition variable
|
||||
# Loop sum 1, 4, 10, ...
|
||||
while i <= n:
|
||||
res += i
|
||||
# Update condition variable
|
||||
i += 1
|
||||
i *= 2
|
||||
return res
|
||||
|
||||
|
||||
def nested_for_loop(n: int) -> str:
|
||||
"""Double for loop"""
|
||||
res = ""
|
||||
# Loop i = 1, 2, ..., n-1, n
|
||||
for i in range(1, n + 1):
|
||||
# Loop j = 1, 2, ..., n-1, n
|
||||
for j in range(1, n + 1):
|
||||
res += f"({i}, {j}), "
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
n = 5
|
||||
res = for_loop(n)
|
||||
print(f"\nfor loop sum result res = {res}")
|
||||
|
||||
res = while_loop(n)
|
||||
print(f"\nwhile loop sum result res = {res}")
|
||||
|
||||
res = while_loop_ii(n)
|
||||
print(f"\nwhile loop (two updates) sum result res = {res}")
|
||||
|
||||
res = nested_for_loop(n)
|
||||
print(f"\nDouble for loop traversal result {res}")
|
||||
@ -0,0 +1,69 @@
|
||||
"""
|
||||
File: recursion.py
|
||||
Created Time: 2023-08-24
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def recur(n: int) -> int:
|
||||
"""Recursion"""
|
||||
# Termination condition
|
||||
if n == 1:
|
||||
return 1
|
||||
# Recursive: recursive call
|
||||
res = recur(n - 1)
|
||||
# Return: return result
|
||||
return n + res
|
||||
|
||||
|
||||
def for_loop_recur(n: int) -> int:
|
||||
"""Simulate recursion with iteration"""
|
||||
# Use an explicit stack to simulate the system call stack
|
||||
stack = []
|
||||
res = 0
|
||||
# Recursive: recursive call
|
||||
for i in range(n, 0, -1):
|
||||
# Simulate "recursive" by "pushing onto the stack"
|
||||
stack.append(i)
|
||||
# Return: return result
|
||||
while stack:
|
||||
# Simulate "return" by "popping from the stack"
|
||||
res += stack.pop()
|
||||
# res = 1+2+3+...+n
|
||||
return res
|
||||
|
||||
|
||||
def tail_recur(n, res):
|
||||
"""Tail recursion"""
|
||||
# Termination condition
|
||||
if n == 0:
|
||||
return res
|
||||
# Tail recursive call
|
||||
return tail_recur(n - 1, res + n)
|
||||
|
||||
|
||||
def fib(n: int) -> int:
|
||||
"""Fibonacci sequence: Recursion"""
|
||||
# Termination condition f(1) = 0, f(2) = 1
|
||||
if n == 1 or n == 2:
|
||||
return n - 1
|
||||
# Recursive call f(n) = f(n-1) + f(n-2)
|
||||
res = fib(n - 1) + fib(n - 2)
|
||||
# Return result f(n)
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
n = 5
|
||||
res = recur(n)
|
||||
print(f"\nRecursive function sum result res = {res}")
|
||||
|
||||
res = for_loop_recur(n)
|
||||
print(f"\nSimulate recursion with iteration sum result res = {res}")
|
||||
|
||||
res = tail_recur(n, 0)
|
||||
print(f"\nTail recursive function sum result res = {res}")
|
||||
|
||||
res = fib(n)
|
||||
print(f"\nThe n th term of the Fibonacci sequence is {res}")
|
||||
@ -0,0 +1,90 @@
|
||||
"""
|
||||
File: space_complexity.py
|
||||
Created Time: 2022-11-25
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import ListNode, TreeNode, print_tree
|
||||
|
||||
|
||||
def function() -> int:
|
||||
"""Function"""
|
||||
# Perform some operations
|
||||
return 0
|
||||
|
||||
|
||||
def constant(n: int):
|
||||
"""Constant complexity"""
|
||||
# Constants, variables, objects occupy O(1) space
|
||||
a = 0
|
||||
nums = [0] * 10000
|
||||
node = ListNode(0)
|
||||
# Variables in a loop occupy O(1) space
|
||||
for _ in range(n):
|
||||
c = 0
|
||||
# Functions in a loop occupy O(1) space
|
||||
for _ in range(n):
|
||||
function()
|
||||
|
||||
|
||||
def linear(n: int):
|
||||
"""Linear complexity"""
|
||||
# A list of length n occupies O(n) space
|
||||
nums = [0] * n
|
||||
# A hash table of length n occupies O(n) space
|
||||
hmap = dict[int, str]()
|
||||
for i in range(n):
|
||||
hmap[i] = str(i)
|
||||
|
||||
|
||||
def linear_recur(n: int):
|
||||
"""Linear complexity (recursive implementation)"""
|
||||
print("Recursive n =", n)
|
||||
if n == 1:
|
||||
return
|
||||
linear_recur(n - 1)
|
||||
|
||||
|
||||
def quadratic(n: int):
|
||||
"""Quadratic complexity"""
|
||||
# A two-dimensional list occupies O(n^2) space
|
||||
num_matrix = [[0] * n for _ in range(n)]
|
||||
|
||||
|
||||
def quadratic_recur(n: int) -> int:
|
||||
"""Quadratic complexity (recursive implementation)"""
|
||||
if n <= 0:
|
||||
return 0
|
||||
# Array nums length = n, n-1, ..., 2, 1
|
||||
nums = [0] * n
|
||||
return quadratic_recur(n - 1)
|
||||
|
||||
|
||||
def build_tree(n: int) -> TreeNode | None:
|
||||
"""Exponential complexity (building a full binary tree)"""
|
||||
if n == 0:
|
||||
return None
|
||||
root = TreeNode(0)
|
||||
root.left = build_tree(n - 1)
|
||||
root.right = build_tree(n - 1)
|
||||
return root
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
n = 5
|
||||
# Constant complexity
|
||||
constant(n)
|
||||
# Linear complexity
|
||||
linear(n)
|
||||
linear_recur(n)
|
||||
# Quadratic complexity
|
||||
quadratic(n)
|
||||
quadratic_recur(n)
|
||||
# Exponential complexity
|
||||
root = build_tree(n)
|
||||
print_tree(root)
|
||||
@ -0,0 +1,151 @@
|
||||
"""
|
||||
File: time_complexity.py
|
||||
Created Time: 2022-11-25
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def constant(n: int) -> int:
|
||||
"""Constant complexity"""
|
||||
count = 0
|
||||
size = 100000
|
||||
for _ in range(size):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def linear(n: int) -> int:
|
||||
"""Linear complexity"""
|
||||
count = 0
|
||||
for _ in range(n):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def array_traversal(nums: list[int]) -> int:
|
||||
"""Linear complexity (traversing an array)"""
|
||||
count = 0
|
||||
# Loop count is proportional to the length of the array
|
||||
for num in nums:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def quadratic(n: int) -> int:
|
||||
"""Quadratic complexity"""
|
||||
count = 0
|
||||
# Loop count is squared in relation to the data size n
|
||||
for i in range(n):
|
||||
for j in range(n):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def bubble_sort(nums: list[int]) -> int:
|
||||
"""Quadratic complexity (bubble sort)"""
|
||||
count = 0 # Counter
|
||||
# Outer loop: unsorted range is [0, i]
|
||||
for i in range(len(nums) - 1, 0, -1):
|
||||
# Inner loop: swap the largest element in the unsorted range [0, i] to the right end of the range
|
||||
for j in range(i):
|
||||
if nums[j] > nums[j + 1]:
|
||||
# Swap nums[j] and nums[j + 1]
|
||||
tmp: int = nums[j]
|
||||
nums[j] = nums[j + 1]
|
||||
nums[j + 1] = tmp
|
||||
count += 3 # Element swap includes 3 individual operations
|
||||
return count
|
||||
|
||||
|
||||
def exponential(n: int) -> int:
|
||||
"""Exponential complexity (loop implementation)"""
|
||||
count = 0
|
||||
base = 1
|
||||
# Cells split into two every round, forming the sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
for _ in range(n):
|
||||
for _ in range(base):
|
||||
count += 1
|
||||
base *= 2
|
||||
# count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
|
||||
return count
|
||||
|
||||
|
||||
def exp_recur(n: int) -> int:
|
||||
"""Exponential complexity (recursive implementation)"""
|
||||
if n == 1:
|
||||
return 1
|
||||
return exp_recur(n - 1) + exp_recur(n - 1) + 1
|
||||
|
||||
|
||||
def logarithmic(n: int) -> int:
|
||||
"""Logarithmic complexity (loop implementation)"""
|
||||
count = 0
|
||||
while n > 1:
|
||||
n = n / 2
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def log_recur(n: int) -> int:
|
||||
"""Logarithmic complexity (recursive implementation)"""
|
||||
if n <= 1:
|
||||
return 0
|
||||
return log_recur(n / 2) + 1
|
||||
|
||||
|
||||
def linear_log_recur(n: int) -> int:
|
||||
"""Linear logarithmic complexity"""
|
||||
if n <= 1:
|
||||
return 1
|
||||
count: int = linear_log_recur(n // 2) + linear_log_recur(n // 2)
|
||||
for _ in range(n):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def factorial_recur(n: int) -> int:
|
||||
"""Factorial complexity (recursive implementation)"""
|
||||
if n == 0:
|
||||
return 1
|
||||
count = 0
|
||||
# From 1 split into n
|
||||
for _ in range(n):
|
||||
count += factorial_recur(n - 1)
|
||||
return count
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Can modify n to experience the trend of operation count changes under various complexities
|
||||
n = 8
|
||||
print("Input data size n =", n)
|
||||
|
||||
count: int = constant(n)
|
||||
print("Constant complexity operation count =", count)
|
||||
|
||||
count: int = linear(n)
|
||||
print("Linear complexity operation count =", count)
|
||||
count: int = array_traversal([0] * n)
|
||||
print("Linear complexity (traversing an array) operation count =", count)
|
||||
|
||||
count: int = quadratic(n)
|
||||
print("Quadratic complexity operation count =", count)
|
||||
nums = [i for i in range(n, 0, -1)] # [n, n-1, ..., 2, 1]
|
||||
count: int = bubble_sort(nums)
|
||||
print("Quadratic complexity (bubble sort) operation count =", count)
|
||||
|
||||
count: int = exponential(n)
|
||||
print("Exponential complexity (loop implementation) operation count =", count)
|
||||
count: int = exp_recur(n)
|
||||
print("Exponential complexity (recursive implementation) operation count =", count)
|
||||
|
||||
count: int = logarithmic(n)
|
||||
print("Logarithmic complexity (loop implementation) operation count =", count)
|
||||
count: int = log_recur(n)
|
||||
print("Logarithmic complexity (recursive implementation) operation count =", count)
|
||||
|
||||
count: int = linear_log_recur(n)
|
||||
print("Linear logarithmic complexity (recursive implementation) operation count =", count)
|
||||
|
||||
count: int = factorial_recur(n)
|
||||
print("Factorial complexity (recursive implementation) operation count =", count)
|
||||
@ -0,0 +1,36 @@
|
||||
"""
|
||||
File: worst_best_time_complexity.py
|
||||
Created Time: 2022-11-25
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
|
||||
def random_numbers(n: int) -> list[int]:
|
||||
"""Generate an array with elements: 1, 2, ..., n, order shuffled"""
|
||||
# Generate array nums =: 1, 2, 3, ..., n
|
||||
nums = [i for i in range(1, n + 1)]
|
||||
# Randomly shuffle array elements
|
||||
random.shuffle(nums)
|
||||
return nums
|
||||
|
||||
|
||||
def find_one(nums: list[int]) -> int:
|
||||
"""Find the index of number 1 in array nums"""
|
||||
for i in range(len(nums)):
|
||||
# When element 1 is at the start of the array, achieve best time complexity O(1)
|
||||
# When element 1 is at the end of the array, achieve worst time complexity O(n)
|
||||
if nums[i] == 1:
|
||||
return i
|
||||
return -1
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
for i in range(10):
|
||||
n = 100
|
||||
nums: list[int] = random_numbers(n)
|
||||
index: int = find_one(nums)
|
||||
print("\nThe array [ 1, 2, ..., n ] after being shuffled =", nums)
|
||||
print("Index of number 1 =", index)
|
||||
Reference in New Issue
Block a user