Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
ZhouYang1993 / heap_sort.py
Created December 27, 2022 21:20
A Deep Dive into Heap and Heap Sort in Python: From Beginner to Expert
def heap_sort(arr):
# Build a max heap from the input list
heapify(arr)
# Extract the root element (the maximum value) and place it at the end of the sorted list
sorted_arr = []
while arr:
sorted_arr.append(heappop(arr))
# Return the sorted list
return sorted_arr
@ZhouYang1993
ZhouYang1993 / radix_sort.py
Created December 26, 2022 22:08
Mastering Radix Sort in Python: A Visual Guide
def radix_sort(arr):
"""
Radix sort starting from the least significant digit(LSD)
:param arr: The list needs to be sorted
:return: A sorted list
"""
# Find the maximum number of digits in the list
max_digits = max([len(str(x)) for x in arr])
# Set the base (radix) to 10
@ZhouYang1993
ZhouYang1993 / prime_factorization.py
Created October 19, 2022 19:54
prime_factorization_in_python
def prime_factorization(num: int):
k = 2
factors = []
while k * k <= num:
while num % k == 0:
factors.append(k)
num //= k
k += 1
@ZhouYang1993
ZhouYang1993 / solution.py
Created October 17, 2022 20:04
LeetCode 2438. Range Product Queries of Powers
class Solution:
def productQueries(self, n: int, queries):
bn = bin(n)[2:][::-1]
powers = []
for i, v in enumerate(bn):
if v == '1':
powers.append(i)
ans = []
for l, r in queries:
t = 0
@ZhouYang1993
ZhouYang1993 / touch_detection.js
Created October 5, 2022 21:41
Detect Mobile Devices in JS
function isMobile() {
try {
object.addEventListener("touchstart", myScript);
return true;
} catch(e) {
return false;
}
}
@ZhouYang1993
ZhouYang1993 / ResponsiveUI.js
Created October 5, 2022 21:27
Detect Mobile Browsers in React
function ResponsiveUI() {
return (
window.screen.width >= 600 ? (
// an UI component for desktop browsers
) : (
// an UI component for mobile browsers
)
)
}
@ZhouYang1993
ZhouYang1993 / check_screen_size.js
Created October 5, 2022 21:21
Detect Devices in JavaScripts
function onClick(){
if(window.screen.width>=600){
// do sth for desktop browsers
}
else{
// do sth for mobile browsers
}
}
@ZhouYang1993
ZhouYang1993 / detect_device.js
Created October 5, 2022 21:10
Detect Mobile Devices in JavaScript
function onClick() {
if ((/Android/i.test(navigator.userAgent))) {
// go to Google Play Store
}
if (/iPad|iPhone|iPod/i.test(navigator.userAgent)) {
// go to App Store
}
else {
// go to another website
}
@ZhouYang1993
ZhouYang1993 / counter.py
Created September 26, 2022 21:14
Counter in Python
from collections import Counter
author = "Yang Zhou"
chars = Counter(author)
print(chars)
# Counter({'Y': 1, 'a': 1, 'n': 1, 'g': 1, ' ': 1, 'Z': 1, 'h': 1, 'o': 1, 'u': 1})
@ZhouYang1993
ZhouYang1993 / sort_dict.py
Created September 26, 2022 21:09
Sorting a Python Dictionary
cities = {'London': '2', 'Tokyo': '3', 'New York': '1'}
print(sorted(cities.items(),key=lambda d:d[1]))
# [('New York', '1'), ('London', '2'), ('Tokyo', '3')]