mirror of
https://github.com/krahets/hello-algo.git
synced 2026-06-30 17:44:26 +00: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,100 @@
|
||||
"""
|
||||
File: array.py
|
||||
Created Time: 2022-11-25
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
|
||||
def random_access(nums: list[int]) -> int:
|
||||
"""Random access to elements"""
|
||||
# Randomly select a number from the interval [0, len(nums)-1]
|
||||
random_index = random.randint(0, len(nums) - 1)
|
||||
# Retrieve and return a random element
|
||||
random_num = nums[random_index]
|
||||
return random_num
|
||||
|
||||
|
||||
# Note that Python's list is a dynamic array that can be extended
|
||||
# For ease of learning, this function treats the list as a static array
|
||||
def extend(nums: list[int], enlarge: int) -> list[int]:
|
||||
"""Extend array length"""
|
||||
# Initialize an extended length array
|
||||
res = [0] * (len(nums) + enlarge)
|
||||
# Copy all elements from the original array to the new array
|
||||
for i in range(len(nums)):
|
||||
res[i] = nums[i]
|
||||
# Return the new array after expansion
|
||||
return res
|
||||
|
||||
|
||||
def insert(nums: list[int], num: int, index: int):
|
||||
"""Insert element num at `index`"""
|
||||
# Move all elements after `index` one position backward
|
||||
for i in range(len(nums) - 1, index, -1):
|
||||
nums[i] = nums[i - 1]
|
||||
# Assign num to the element at index
|
||||
nums[index] = num
|
||||
|
||||
|
||||
def remove(nums: list[int], index: int):
|
||||
"""Remove the element at `index`"""
|
||||
# Move all elements after `index` one position forward
|
||||
for i in range(index, len(nums) - 1):
|
||||
nums[i] = nums[i + 1]
|
||||
|
||||
|
||||
def traverse(nums: list[int]):
|
||||
"""Traverse array"""
|
||||
count = 0
|
||||
# Traverse array by index
|
||||
for i in range(len(nums)):
|
||||
count += nums[i]
|
||||
# Traverse array elements
|
||||
for num in nums:
|
||||
count += num
|
||||
# Traverse both data index and elements
|
||||
for i, num in enumerate(nums):
|
||||
count += nums[i]
|
||||
count += num
|
||||
|
||||
|
||||
def find(nums: list[int], target: int) -> int:
|
||||
"""Search for a specified element in the array"""
|
||||
for i in range(len(nums)):
|
||||
if nums[i] == target:
|
||||
return i
|
||||
return -1
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize an array
|
||||
arr = [0] * 5
|
||||
print("Array arr =", arr)
|
||||
nums = [1, 3, 2, 5, 4]
|
||||
print("Array nums =", nums)
|
||||
|
||||
# Random access
|
||||
random_num: int = random_access(nums)
|
||||
print("Retrieve a random element in nums", random_num)
|
||||
|
||||
# Length extension
|
||||
nums: list[int] = extend(nums, 3)
|
||||
print("Extend the array length to 8, resulting in nums =", nums)
|
||||
|
||||
# Insert element
|
||||
insert(nums, 6, 3)
|
||||
print("Insert number 6 at index 3, resulting in nums =", nums)
|
||||
|
||||
# Remove element
|
||||
remove(nums, 2)
|
||||
print("Remove the element at index 2, resulting in nums =", nums)
|
||||
|
||||
# Traverse array
|
||||
traverse(nums)
|
||||
|
||||
# Search for elements
|
||||
index: int = find(nums, 3)
|
||||
print("Search for element 3 in nums, resulting in index =", index)
|
||||
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
File: linked_list.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, print_linked_list
|
||||
|
||||
|
||||
def insert(n0: ListNode, P: ListNode):
|
||||
"""Insert node P after node n0 in the linked list"""
|
||||
n1 = n0.next
|
||||
P.next = n1
|
||||
n0.next = P
|
||||
|
||||
|
||||
def remove(n0: ListNode):
|
||||
"""Remove the first node after node n0 in the linked list"""
|
||||
if not n0.next:
|
||||
return
|
||||
# n0 -> P -> n1
|
||||
P = n0.next
|
||||
n1 = P.next
|
||||
n0.next = n1
|
||||
|
||||
|
||||
def access(head: ListNode, index: int) -> ListNode | None:
|
||||
"""Access the node at `index` in the linked list"""
|
||||
for _ in range(index):
|
||||
if not head:
|
||||
return None
|
||||
head = head.next
|
||||
return head
|
||||
|
||||
|
||||
def find(head: ListNode, target: int) -> int:
|
||||
"""Search for the first node with value target in the linked list"""
|
||||
index = 0
|
||||
while head:
|
||||
if head.val == target:
|
||||
return index
|
||||
head = head.next
|
||||
index += 1
|
||||
return -1
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize linked list
|
||||
# Initialize each node
|
||||
n0 = ListNode(1)
|
||||
n1 = ListNode(3)
|
||||
n2 = ListNode(2)
|
||||
n3 = ListNode(5)
|
||||
n4 = ListNode(4)
|
||||
# Build references between nodes
|
||||
n0.next = n1
|
||||
n1.next = n2
|
||||
n2.next = n3
|
||||
n3.next = n4
|
||||
print("The initialized linked list is")
|
||||
print_linked_list(n0)
|
||||
|
||||
# Insert node
|
||||
p = ListNode(0)
|
||||
insert(n0, p)
|
||||
print("Linked list after inserting the node is")
|
||||
print_linked_list(n0)
|
||||
|
||||
# Remove node
|
||||
remove(n0)
|
||||
print("Linked list after removing the node is")
|
||||
print_linked_list(n0)
|
||||
|
||||
# Access node
|
||||
node: ListNode = access(n0, 3)
|
||||
print("The value of the node at index 3 in the linked list = {}".format(node.val))
|
||||
|
||||
# Search node
|
||||
index: int = find(n0, 2)
|
||||
print("The index of the node with value 2 in the linked list = {}".format(index))
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
File: list.py
|
||||
Created Time: 2022-11-25
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize list
|
||||
nums: list[int] = [1, 3, 2, 5, 4]
|
||||
print("\nList nums =", nums)
|
||||
|
||||
# Access element
|
||||
x: int = nums[1]
|
||||
print("\nAccess the element at index 1, resulting in x =", x)
|
||||
|
||||
# Update element
|
||||
nums[1] = 0
|
||||
print("\nUpdate the element at index 1 to 0, resulting in nums =", nums)
|
||||
|
||||
# Clear list
|
||||
nums.clear()
|
||||
print("\nAfter clearing the list, nums =", nums)
|
||||
|
||||
# Add element at the end
|
||||
nums.append(1)
|
||||
nums.append(3)
|
||||
nums.append(2)
|
||||
nums.append(5)
|
||||
nums.append(4)
|
||||
print("\nAfter adding the element, nums =", nums)
|
||||
|
||||
# Insert element in the middle
|
||||
nums.insert(3, 6)
|
||||
print("\nInsert number 6 at index 3, resulting in nums =", nums)
|
||||
|
||||
# Remove element
|
||||
nums.pop(3)
|
||||
print("\nRemove the element at index 3, resulting in nums =", nums)
|
||||
|
||||
# Traverse the list by index
|
||||
count = 0
|
||||
for i in range(len(nums)):
|
||||
count += nums[i]
|
||||
# Traverse the list elements
|
||||
for num in nums:
|
||||
count += num
|
||||
|
||||
# Concatenate two lists
|
||||
nums1 = [6, 8, 7, 10, 9]
|
||||
nums += nums1
|
||||
print("\nConcatenate list nums1 to nums, resulting in nums =", nums)
|
||||
|
||||
# Sort list
|
||||
nums.sort()
|
||||
print("\nAfter sorting the list, nums =", nums)
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
File: my_list.py
|
||||
Created Time: 2022-11-25
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
class MyList:
|
||||
"""List class"""
|
||||
|
||||
def __init__(self):
|
||||
"""Constructor"""
|
||||
self._capacity: int = 10 # List capacity
|
||||
self._arr: list[int] = [0] * self._capacity # Array (stores list elements)
|
||||
self._size: int = 0 # List length (current number of elements)
|
||||
self._extend_ratio: int = 2 # Multiple for each list expansion
|
||||
|
||||
def size(self) -> int:
|
||||
"""Get list length (current number of elements)"""
|
||||
return self._size
|
||||
|
||||
def capacity(self) -> int:
|
||||
"""Get list capacity"""
|
||||
return self._capacity
|
||||
|
||||
def get(self, index: int) -> int:
|
||||
"""Access element"""
|
||||
# If the index is out of bounds, throw an exception, as below
|
||||
if index < 0 or index >= self._size:
|
||||
raise IndexError("Index out of bounds")
|
||||
return self._arr[index]
|
||||
|
||||
def set(self, num: int, index: int):
|
||||
"""Update element"""
|
||||
if index < 0 or index >= self._size:
|
||||
raise IndexError("Index out of bounds")
|
||||
self._arr[index] = num
|
||||
|
||||
def add(self, num: int):
|
||||
"""Add element at the end"""
|
||||
# When the number of elements exceeds capacity, trigger the expansion mechanism
|
||||
if self.size() == self.capacity():
|
||||
self.extend_capacity()
|
||||
self._arr[self._size] = num
|
||||
self._size += 1
|
||||
|
||||
def insert(self, num: int, index: int):
|
||||
"""Insert element in the middle"""
|
||||
if index < 0 or index >= self._size:
|
||||
raise IndexError("Index out of bounds")
|
||||
# When the number of elements exceeds capacity, trigger the expansion mechanism
|
||||
if self._size == self.capacity():
|
||||
self.extend_capacity()
|
||||
# Move all elements after `index` one position backward
|
||||
for j in range(self._size - 1, index - 1, -1):
|
||||
self._arr[j + 1] = self._arr[j]
|
||||
self._arr[index] = num
|
||||
# Update the number of elements
|
||||
self._size += 1
|
||||
|
||||
def remove(self, index: int) -> int:
|
||||
"""Remove element"""
|
||||
if index < 0 or index >= self._size:
|
||||
raise IndexError("Index out of bounds")
|
||||
num = self._arr[index]
|
||||
# Move all elements after `index` one position forward
|
||||
for j in range(index, self._size - 1):
|
||||
self._arr[j] = self._arr[j + 1]
|
||||
# Update the number of elements
|
||||
self._size -= 1
|
||||
# Return the removed element
|
||||
return num
|
||||
|
||||
def extend_capacity(self):
|
||||
"""Extend list"""
|
||||
# Create a new array of _extend_ratio times the length of the original array and copy the original array to the new array
|
||||
self._arr = self._arr + [0] * self.capacity() * (self._extend_ratio - 1)
|
||||
# Update list capacity
|
||||
self._capacity = len(self._arr)
|
||||
|
||||
def to_array(self) -> list[int]:
|
||||
"""Return a list of valid lengths"""
|
||||
return self._arr[: self._size]
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize list
|
||||
nums = MyList()
|
||||
# Add element at the end
|
||||
nums.add(1)
|
||||
nums.add(3)
|
||||
nums.add(2)
|
||||
nums.add(5)
|
||||
nums.add(4)
|
||||
print(f"List nums = {nums.to_array()} ,capacity = {nums.capacity()} ,length = {nums.size()}")
|
||||
|
||||
# Insert element in the middle
|
||||
nums.insert(6, index=3)
|
||||
print("Insert number 6 at index 3, resulting in nums =", nums.to_array())
|
||||
|
||||
# Remove element
|
||||
nums.remove(3)
|
||||
print("Remove the element at index 3, resulting in nums =", nums.to_array())
|
||||
|
||||
# Access element
|
||||
num = nums.get(1)
|
||||
print("Access the element at index 1, resulting in num =", num)
|
||||
|
||||
# Update element
|
||||
nums.set(0, 1)
|
||||
print("Update the element at index 1 to 0, resulting in nums =", nums.to_array())
|
||||
|
||||
# Test expansion mechanism
|
||||
for i in range(10):
|
||||
# At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism at this time
|
||||
nums.add(i)
|
||||
print(f"After expansion, the list {nums.to_array()} ,capacity = {nums.capacity()} ,length = {nums.size()}")
|
||||
Reference in New Issue
Block a user