mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-10 16:00:36 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -6,7 +6,7 @@ Author: Hello Algo Team
|
||||
|
||||
|
||||
def sum_iter(n: int) -> int:
|
||||
"""Iterative summation"""
|
||||
"""Sum using iteration"""
|
||||
res = 0
|
||||
for i in range(1, n + 1):
|
||||
res += i
|
||||
@@ -14,14 +14,14 @@ def sum_iter(n: int) -> int:
|
||||
|
||||
|
||||
def sum_recur(n: int) -> int:
|
||||
"""Recursive summation"""
|
||||
"""Sum using recursion"""
|
||||
if n == 1:
|
||||
return 1
|
||||
return n + sum_recur(n - 1)
|
||||
|
||||
|
||||
def linear_loop(n: int) -> int:
|
||||
"""Linear loop"""
|
||||
"""Linear-time loop"""
|
||||
res = 0
|
||||
for i in range(n):
|
||||
res += i
|
||||
@@ -29,7 +29,7 @@ def linear_loop(n: int) -> int:
|
||||
|
||||
|
||||
def quadratic_loop(n: int) -> int:
|
||||
"""Quadratic loop"""
|
||||
"""Quadratic-time loop"""
|
||||
res = 0
|
||||
for i in range(n):
|
||||
for j in range(i, n):
|
||||
@@ -38,7 +38,7 @@ def quadratic_loop(n: int) -> int:
|
||||
|
||||
|
||||
def logarithmic_loop(n: int) -> int:
|
||||
"""Logarithmic loop"""
|
||||
"""Logarithmic-time loop"""
|
||||
while n > 1:
|
||||
n //= 2
|
||||
return n
|
||||
|
||||
@@ -8,7 +8,7 @@ Author: krahets (krahets@163.com)
|
||||
def for_loop(n: int) -> int:
|
||||
"""for loop"""
|
||||
res = 0
|
||||
# Sum 1, 2, ..., n-1, n
|
||||
# Sum 1, 2, ..., n-1, n in a loop
|
||||
for i in range(1, n + 1):
|
||||
res += i
|
||||
return res
|
||||
@@ -17,49 +17,49 @@ def for_loop(n: int) -> int:
|
||||
def while_loop(n: int) -> int:
|
||||
"""while loop"""
|
||||
res = 0
|
||||
i = 1 # Initialize condition variable
|
||||
# Sum 1, 2, ..., n-1, n
|
||||
i = 1 # Initialize the loop control variable
|
||||
# Sum 1, 2, ..., n-1, n in a loop
|
||||
while i <= n:
|
||||
res += i
|
||||
i += 1 # Update condition variable
|
||||
i += 1 # Update the loop control variable
|
||||
return res
|
||||
|
||||
|
||||
def while_loop_ii(n: int) -> int:
|
||||
"""while loop (two updates)"""
|
||||
res = 0
|
||||
i = 1 # Initialize condition variable
|
||||
# Sum 1, 4, 10, ...
|
||||
i = 1 # Initialize the loop control variable
|
||||
# Sum 1, 4, 10, ... in a loop
|
||||
while i <= n:
|
||||
res += i
|
||||
# Update condition variable
|
||||
# Update the loop control variable
|
||||
i += 1
|
||||
i *= 2
|
||||
return res
|
||||
|
||||
|
||||
def nested_for_loop(n: int) -> str:
|
||||
"""Nested for loop"""
|
||||
"""Nested for loops"""
|
||||
res = ""
|
||||
# Loop i = 1, 2, ..., n-1, n
|
||||
# Loop over i = 1, 2, ..., n-1, n
|
||||
for i in range(1, n + 1):
|
||||
# Loop j = 1, 2, ..., n-1, n
|
||||
# Loop over j = 1, 2, ..., n-1, n
|
||||
for j in range(1, n + 1):
|
||||
res += f"({i}, {j}), "
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
n = 5
|
||||
res = for_loop(n)
|
||||
print(f"\nSum result of for loop res = {res}")
|
||||
print(f"\nSum from the for loop: res = {res}")
|
||||
|
||||
res = while_loop(n)
|
||||
print(f"\nSum result of while loop res = {res}")
|
||||
print(f"\nSum from the while loop: res = {res}")
|
||||
|
||||
res = while_loop_ii(n)
|
||||
print(f"\nSum result of while loop (two updates) res = {res}")
|
||||
print(f"\nSum from the while loop (two updates): res = {res}")
|
||||
|
||||
res = nested_for_loop(n)
|
||||
print(f"\nTraversal result of nested for loop {res}")
|
||||
print(f"\nTraversal from the nested for loops: {res}")
|
||||
|
||||
@@ -7,12 +7,12 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
def recur(n: int) -> int:
|
||||
"""Recursion"""
|
||||
# Termination condition
|
||||
# Base case
|
||||
if n == 1:
|
||||
return 1
|
||||
# Recurse: recursive call
|
||||
# Recurse: make a recursive call
|
||||
res = recur(n - 1)
|
||||
# Return: return result
|
||||
# Unwind: return the result
|
||||
return n + res
|
||||
|
||||
|
||||
@@ -21,13 +21,13 @@ def for_loop_recur(n: int) -> int:
|
||||
# Use an explicit stack to simulate the system call stack
|
||||
stack = []
|
||||
res = 0
|
||||
# Recurse: recursive call
|
||||
# Simulate the recursive-call phase
|
||||
for i in range(n, 0, -1):
|
||||
# Simulate "recurse" with "push"
|
||||
# Simulate recursive calls by pushing onto the stack
|
||||
stack.append(i)
|
||||
# Return: return result
|
||||
# Simulate unwinding and accumulating the result
|
||||
while stack:
|
||||
# Simulate "return" with "pop"
|
||||
# Simulate unwinding by popping from the stack
|
||||
res += stack.pop()
|
||||
# res = 1+2+3+...+n
|
||||
return res
|
||||
@@ -35,35 +35,35 @@ def for_loop_recur(n: int) -> int:
|
||||
|
||||
def tail_recur(n, res):
|
||||
"""Tail recursion"""
|
||||
# Termination condition
|
||||
# Base case
|
||||
if n == 0:
|
||||
return res
|
||||
# Tail recursive call
|
||||
# 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
|
||||
# Base cases: 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)
|
||||
# Recursive calls: f(n) = f(n-1) + f(n-2)
|
||||
res = fib(n - 1) + fib(n - 2)
|
||||
# Return result f(n)
|
||||
# Return the result f(n)
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
n = 5
|
||||
res = recur(n)
|
||||
print(f"\nSum result of recursive function res = {res}")
|
||||
print(f"\nSum from the recursive function: res = {res}")
|
||||
|
||||
res = for_loop_recur(n)
|
||||
print(f"\nSum result of simulating recursion using iteration res = {res}")
|
||||
print(f"\nSum from simulating recursion using iteration: res = {res}")
|
||||
|
||||
res = tail_recur(n, 0)
|
||||
print(f"\nSum result of tail recursive function res = {res}")
|
||||
print(f"\nSum from the tail-recursive function: res = {res}")
|
||||
|
||||
res = fib(n)
|
||||
print(f"\nThe {n}th term of the Fibonacci sequence is {res}")
|
||||
print(f"\nTerm {n} of the Fibonacci sequence is {res}")
|
||||
|
||||
@@ -18,54 +18,54 @@ def function() -> int:
|
||||
|
||||
|
||||
def constant(n: int):
|
||||
"""Constant order"""
|
||||
# Constants, variables, objects occupy O(1) space
|
||||
"""Constant complexity"""
|
||||
# Constants, variables, and objects occupy O(1) space
|
||||
a = 0
|
||||
nums = [0] * 10000
|
||||
node = ListNode(0)
|
||||
# Variables in the loop occupy O(1) space
|
||||
for _ in range(n):
|
||||
c = 0
|
||||
# Functions in the loop occupy O(1) space
|
||||
# Function calls in the loop occupy O(1) space
|
||||
for _ in range(n):
|
||||
function()
|
||||
|
||||
|
||||
def linear(n: int):
|
||||
"""Linear order"""
|
||||
"""Linear complexity"""
|
||||
# A list of length n occupies O(n) space
|
||||
nums = [0] * n
|
||||
# A hash table of length n occupies O(n) space
|
||||
# A hash table with n entries occupies O(n) space
|
||||
hmap = dict[int, str]()
|
||||
for i in range(n):
|
||||
hmap[i] = str(i)
|
||||
|
||||
|
||||
def linear_recur(n: int):
|
||||
"""Linear order (recursive implementation)"""
|
||||
print("Recursion n =", n)
|
||||
"""Linear complexity (recursive implementation)"""
|
||||
print("Recursion: n =", n)
|
||||
if n == 1:
|
||||
return
|
||||
linear_recur(n - 1)
|
||||
|
||||
|
||||
def quadratic(n: int):
|
||||
"""Quadratic order"""
|
||||
# A 2D list occupies O(n^2) space
|
||||
"""Quadratic complexity"""
|
||||
# The two-dimensional list occupies O(n^2) space
|
||||
num_matrix = [[0] * n for _ in range(n)]
|
||||
|
||||
|
||||
def quadratic_recur(n: int) -> int:
|
||||
"""Quadratic order (recursive implementation)"""
|
||||
"""Quadratic complexity (recursive implementation)"""
|
||||
if n <= 0:
|
||||
return 0
|
||||
# Array nums length is n, n-1, ..., 2, 1
|
||||
# The lengths of array nums are n, n-1, ..., 2, 1
|
||||
nums = [0] * n
|
||||
return quadratic_recur(n - 1)
|
||||
|
||||
|
||||
def build_tree(n: int) -> TreeNode | None:
|
||||
"""Exponential order (build full binary tree)"""
|
||||
"""Exponential complexity (building a perfect binary tree)"""
|
||||
if n == 0:
|
||||
return None
|
||||
root = TreeNode(0)
|
||||
@@ -74,17 +74,17 @@ def build_tree(n: int) -> TreeNode | None:
|
||||
return root
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
n = 5
|
||||
# Constant order
|
||||
# Constant complexity
|
||||
constant(n)
|
||||
# Linear order
|
||||
# Linear complexity
|
||||
linear(n)
|
||||
linear_recur(n)
|
||||
# Quadratic order
|
||||
# Quadratic complexity
|
||||
quadratic(n)
|
||||
quadratic_recur(n)
|
||||
# Exponential order
|
||||
# Exponential complexity
|
||||
root = build_tree(n)
|
||||
print_tree(root)
|
||||
|
||||
@@ -6,7 +6,7 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
|
||||
def constant(n: int) -> int:
|
||||
"""Constant order"""
|
||||
"""Constant complexity"""
|
||||
count = 0
|
||||
size = 100000
|
||||
for _ in range(size):
|
||||
@@ -15,7 +15,7 @@ def constant(n: int) -> int:
|
||||
|
||||
|
||||
def linear(n: int) -> int:
|
||||
"""Linear order"""
|
||||
"""Linear complexity"""
|
||||
count = 0
|
||||
for _ in range(n):
|
||||
count += 1
|
||||
@@ -23,18 +23,18 @@ def linear(n: int) -> int:
|
||||
|
||||
|
||||
def array_traversal(nums: list[int]) -> int:
|
||||
"""Linear order (traversing array)"""
|
||||
"""Linear complexity (array traversal)"""
|
||||
count = 0
|
||||
# Number of iterations is proportional to the array length
|
||||
# The number of iterations is proportional to the array length
|
||||
for num in nums:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def quadratic(n: int) -> int:
|
||||
"""Quadratic order"""
|
||||
"""Quadratic complexity"""
|
||||
count = 0
|
||||
# Number of iterations is quadratically related to the data size n
|
||||
# The number of iterations is proportional to the square of the input size n
|
||||
for i in range(n):
|
||||
for j in range(n):
|
||||
count += 1
|
||||
@@ -42,26 +42,26 @@ def quadratic(n: int) -> int:
|
||||
|
||||
|
||||
def bubble_sort(nums: list[int]) -> int:
|
||||
"""Quadratic order (bubble sort)"""
|
||||
"""Quadratic complexity (bubble sort)"""
|
||||
count = 0 # Counter
|
||||
# Outer loop: unsorted range is [0, i]
|
||||
# Outer loop: the 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 rightmost end of that range
|
||||
# Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
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 unit operations
|
||||
count += 3 # Swapping two elements takes 3 elementary operations
|
||||
return count
|
||||
|
||||
|
||||
def exponential(n: int) -> int:
|
||||
"""Exponential order (loop implementation)"""
|
||||
"""Exponential complexity (iterative implementation)"""
|
||||
count = 0
|
||||
base = 1
|
||||
# Cells divide into two every round, forming sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
# Each cell divides into two per round, giving the sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
for _ in range(n):
|
||||
for _ in range(base):
|
||||
count += 1
|
||||
@@ -71,14 +71,14 @@ def exponential(n: int) -> int:
|
||||
|
||||
|
||||
def exp_recur(n: int) -> int:
|
||||
"""Exponential order (recursive implementation)"""
|
||||
"""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 order (loop implementation)"""
|
||||
"""Logarithmic complexity (iterative implementation)"""
|
||||
count = 0
|
||||
while n > 1:
|
||||
n = n / 2
|
||||
@@ -87,67 +87,67 @@ def logarithmic(n: int) -> int:
|
||||
|
||||
|
||||
def log_recur(n: int) -> int:
|
||||
"""Logarithmic order (recursive implementation)"""
|
||||
"""Logarithmic complexity (recursive implementation)"""
|
||||
if n <= 1:
|
||||
return 0
|
||||
return log_recur(n / 2) + 1
|
||||
|
||||
|
||||
def linear_log_recur(n: int) -> int:
|
||||
"""Linearithmic order"""
|
||||
"""Linearithmic complexity"""
|
||||
if n <= 1:
|
||||
return 1
|
||||
# Divide into two, the scale of subproblems is reduced by half
|
||||
# Split into two subproblems, each half the original size
|
||||
count = linear_log_recur(n // 2) + linear_log_recur(n // 2)
|
||||
# Current subproblem contains n operations
|
||||
# The current subproblem includes n operations
|
||||
for _ in range(n):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def factorial_recur(n: int) -> int:
|
||||
"""Factorial order (recursive implementation)"""
|
||||
"""Factorial complexity (recursive implementation)"""
|
||||
if n == 0:
|
||||
return 1
|
||||
count = 0
|
||||
# Split from 1 into n
|
||||
# Split one problem into n subproblems
|
||||
for _ in range(n):
|
||||
count += factorial_recur(n - 1)
|
||||
return count
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# You can modify n to run and observe the trend of the number of operations for various complexities
|
||||
# Try different values of n to see how the operation count grows for each complexity
|
||||
n = 8
|
||||
print("Input data size n =", n)
|
||||
print("Input size n =", n)
|
||||
|
||||
count = constant(n)
|
||||
print("Number of operations of constant order =", count)
|
||||
print("Operation count for constant complexity =", count)
|
||||
|
||||
count = linear(n)
|
||||
print("Number of operations of linear order =", count)
|
||||
print("Operation count for linear complexity =", count)
|
||||
count = array_traversal([0] * n)
|
||||
print("Number of operations of linear order (traversing array) =", count)
|
||||
print("Operation count for linear complexity (array traversal) =", count)
|
||||
|
||||
count = quadratic(n)
|
||||
print("Number of operations of quadratic order =", count)
|
||||
print("Operation count for quadratic complexity =", count)
|
||||
nums = [i for i in range(n, 0, -1)] # [n, n-1, ..., 2, 1]
|
||||
count = bubble_sort(nums)
|
||||
print("Number of operations of quadratic order (bubble sort) =", count)
|
||||
print("Operation count for quadratic complexity (bubble sort) =", count)
|
||||
|
||||
count = exponential(n)
|
||||
print("Number of operations of exponential order (loop implementation) =", count)
|
||||
print("Operation count for exponential complexity (iterative implementation) =", count)
|
||||
count = exp_recur(n)
|
||||
print("Number of operations of exponential order (recursive implementation) =", count)
|
||||
print("Operation count for exponential complexity (recursive implementation) =", count)
|
||||
|
||||
count = logarithmic(n)
|
||||
print("Number of operations of logarithmic order (loop implementation) =", count)
|
||||
print("Operation count for logarithmic complexity (iterative implementation) =", count)
|
||||
count = log_recur(n)
|
||||
print("Number of operations of logarithmic order (recursive implementation) =", count)
|
||||
print("Operation count for logarithmic complexity (recursive implementation) =", count)
|
||||
|
||||
count = linear_log_recur(n)
|
||||
print("Number of operations of linearithmic order (recursive implementation) =", count)
|
||||
print("Operation count for linearithmic complexity (recursive implementation) =", count)
|
||||
|
||||
count = factorial_recur(n)
|
||||
print("Number of operations of factorial order (recursive implementation) =", count)
|
||||
print("Operation count for factorial complexity (recursive implementation) =", count)
|
||||
|
||||
@@ -8,29 +8,29 @@ import random
|
||||
|
||||
|
||||
def random_numbers(n: int) -> list[int]:
|
||||
"""Generate an array with elements: 1, 2, ..., n, shuffled in order"""
|
||||
# Generate array nums =: 1, 2, 3, ..., n
|
||||
"""Generate an array containing 1, 2, ..., n in shuffled order"""
|
||||
# Generate the array nums = 1, 2, 3, ..., n
|
||||
nums = [i for i in range(1, n + 1)]
|
||||
# Randomly shuffle array elements
|
||||
# Randomly shuffle the array elements
|
||||
random.shuffle(nums)
|
||||
return nums
|
||||
|
||||
|
||||
def find_one(nums: list[int]) -> int:
|
||||
"""Find the index of number 1 in array nums"""
|
||||
"""Find the index of the number 1 in array nums"""
|
||||
for i in range(len(nums)):
|
||||
# When element 1 is at the head of the array, best time complexity O(1) is achieved
|
||||
# When element 1 is at the tail of the array, worst time complexity O(n) is achieved
|
||||
# When 1 is at the start of the array, the best-case time complexity is O(1)
|
||||
# When 1 is at the end of the array, the worst-case time complexity is O(n)
|
||||
if nums[i] == 1:
|
||||
return i
|
||||
return -1
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
for i in range(10):
|
||||
n = 100
|
||||
nums: list[int] = random_numbers(n)
|
||||
index: int = find_one(nums)
|
||||
print("\nArray [ 1, 2, ..., n ] after being shuffled =", nums)
|
||||
print("The index of number 1 is", index)
|
||||
print("\nArray [ 1, 2, ..., n ] after shuffling =", nums)
|
||||
print("The index of the number 1 is", index)
|
||||
|
||||
Reference in New Issue
Block a user