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:
Yudong Jin
2024-05-06 05:21:51 +08:00
committed by GitHub
parent b5e198db7d
commit 1c0f350ad6
174 changed files with 12349 additions and 0 deletions

View File

@ -0,0 +1,71 @@
"""
File: heap.py
Created Time: 2023-02-23
Author: krahets (krahets@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import print_heap
import heapq
def test_push(heap: list, val: int, flag: int = 1):
heapq.heappush(heap, flag * val) # Push the element into heap
print(f"\nElement {val} after pushed into heap")
print_heap([flag * val for val in heap])
def test_pop(heap: list, flag: int = 1):
val = flag * heapq.heappop(heap) # Pop the element at the heap top
print(f"\nHeap top element {val} after exiting heap")
print_heap([flag * val for val in heap])
"""Driver Code"""
if __name__ == "__main__":
# Initialize min-heap
min_heap, flag = [], 1
# Initialize max-heap
max_heap, flag = [], -1
print("\nThe following test case is for max-heap")
# Python's heapq module implements min-heap by default
# Consider "negating the elements" before entering the heap, thus reversing the comparator to implement a max-heap
# In this example, flag = 1 corresponds to min-heap, flag = -1 corresponds to max-heap
# Push the element into heap
test_push(max_heap, 1, flag)
test_push(max_heap, 3, flag)
test_push(max_heap, 2, flag)
test_push(max_heap, 5, flag)
test_push(max_heap, 4, flag)
# Access heap top element
peek: int = flag * max_heap[0]
print(f"\nHeap top element is {peek}")
# Pop the element at the heap top
test_pop(max_heap, flag)
test_pop(max_heap, flag)
test_pop(max_heap, flag)
test_pop(max_heap, flag)
test_pop(max_heap, flag)
# Get heap size
size: int = len(max_heap)
print(f"\nNumber of heap elements is {size}")
# Determine if heap is empty
is_empty: bool = not max_heap
print(f"\nIs the heap empty {is_empty}")
# Enter list and build heap
# Time complexity is O(n), not O(nlogn)
min_heap = [1, 3, 2, 5, 4]
heapq.heapify(min_heap)
print("\nEnter list and build min-heap")
print_heap(min_heap)

View File

@ -0,0 +1,137 @@
"""
File: my_heap.py
Created Time: 2023-02-23
Author: krahets (krahets@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import print_heap
class MaxHeap:
"""Max-heap"""
def __init__(self, nums: list[int]):
"""Constructor, build heap based on input list"""
# Add all list elements into the heap
self.max_heap = nums
# Heapify all nodes except leaves
for i in range(self.parent(self.size() - 1), -1, -1):
self.sift_down(i)
def left(self, i: int) -> int:
"""Get index of left child node"""
return 2 * i + 1
def right(self, i: int) -> int:
"""Get index of right child node"""
return 2 * i + 2
def parent(self, i: int) -> int:
"""Get index of parent node"""
return (i - 1) // 2 # Integer division down
def swap(self, i: int, j: int):
"""Swap elements"""
self.max_heap[i], self.max_heap[j] = self.max_heap[j], self.max_heap[i]
def size(self) -> int:
"""Get heap size"""
return len(self.max_heap)
def is_empty(self) -> bool:
"""Determine if heap is empty"""
return self.size() == 0
def peek(self) -> int:
"""Access heap top element"""
return self.max_heap[0]
def push(self, val: int):
"""Push the element into heap"""
# Add node
self.max_heap.append(val)
# Heapify from bottom to top
self.sift_up(self.size() - 1)
def sift_up(self, i: int):
"""Start heapifying node i, from bottom to top"""
while True:
# Get parent node of node i
p = self.parent(i)
# When "crossing the root node" or "node does not need repair", end heapification
if p < 0 or self.max_heap[i] <= self.max_heap[p]:
break
# Swap two nodes
self.swap(i, p)
# Loop upwards heapification
i = p
def pop(self) -> int:
"""Element exits heap"""
# Empty handling
if self.is_empty():
raise IndexError("Heap is empty")
# Swap the root node with the rightmost leaf node (swap the first element with the last element)
self.swap(0, self.size() - 1)
# Remove node
val = self.max_heap.pop()
# Heapify from top to bottom
self.sift_down(0)
# Return heap top element
return val
def sift_down(self, i: int):
"""Start heapifying node i, from top to bottom"""
while True:
# Determine the largest node among i, l, r, noted as ma
l, r, ma = self.left(i), self.right(i), i
if l < self.size() and self.max_heap[l] > self.max_heap[ma]:
ma = l
if r < self.size() and self.max_heap[r] > self.max_heap[ma]:
ma = r
# If node i is the largest or indices l, r are out of bounds, no further heapification needed, break
if ma == i:
break
# Swap two nodes
self.swap(i, ma)
# Loop downwards heapification
i = ma
def print(self):
"""Print heap (binary tree)"""
print_heap(self.max_heap)
"""Driver Code"""
if __name__ == "__main__":
# Initialize max-heap
max_heap = MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2])
print("\nEnter list and build heap")
max_heap.print()
# Access heap top element
peek = max_heap.peek()
print(f"\nHeap top element is {peek}")
# Push the element into heap
val = 7
max_heap.push(val)
print(f"\nElement {val} after pushed into heap")
max_heap.print()
# Pop the element at the heap top
peek = max_heap.pop()
print(f"\nHeap top element {peek} after exiting heap")
max_heap.print()
# Get heap size
size = max_heap.size()
print(f"\nNumber of heap elements is {size}")
# Determine if heap is empty
is_empty = max_heap.is_empty()
print(f"\nIs the heap empty {is_empty}")

View File

@ -0,0 +1,39 @@
"""
File: top_k.py
Created Time: 2023-06-10
Author: krahets (krahets@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import print_heap
import heapq
def top_k_heap(nums: list[int], k: int) -> list[int]:
"""Using heap to find the largest k elements in an array"""
# Initialize min-heap
heap = []
# Enter the first k elements of the array into the heap
for i in range(k):
heapq.heappush(heap, nums[i])
# From the k+1th element, keep the heap length as k
for i in range(k, len(nums)):
# If the current element is larger than the heap top element, remove the heap top element and enter the current element into the heap
if nums[i] > heap[0]:
heapq.heappop(heap)
heapq.heappush(heap, nums[i])
return heap
"""Driver Code"""
if __name__ == "__main__":
nums = [1, 7, 6, 3, 2]
k = 3
res = top_k_heap(nums, k)
print(f"The largest {k} elements are")
print_heap(res)