You can download this code by clicking the button below.
This code is now available for download.
This function contains a series of functionalities selected from built-in libraries, including generating a unique identifier, inserting into a sorted list, finding the maximum heap element, run-length encoding, calculating the highest common factor, calculating the factorial, and the Fisher-Yates shuffle algorithm.
Technology Stack : array, bisect, collections, functools, heapq, math, operator, random, string
Code Type : Function
Code Difficulty : Intermediate
def aordb(arg1, arg2):
import array
import bisect
from collections import deque
import functools
import heapq
import math
import operator
import random
import string
def generate_unique_id(length=8):
# Generate a unique identifier using random choice from string.ascii_letters and string.digits
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
def insert_sorted(array_list, item):
# Insert an item into a sorted array while maintaining order
bisect.insort(array_list, item)
def find_max_heap(heap_list):
# Return the maximum item from a max heap
return heapq.heappop(heap_list)
def run_length_encode(data_list):
# Run-length encode a list of data
encoded = []
last_item = None
count = 1
for item in data_list:
if item != last_item:
if last_item is not None:
encoded.append((last_item, count))
last_item = item
count = 1
else:
count += 1
if last_item is not None:
encoded.append((last_item, count))
return encoded
def calculate_hcf(x, y):
# Calculate the Highest Common Factor (HCF) of two numbers using Euclid's algorithm
while(y):
x, y = y, x % y
return x
def factorial(n):
# Calculate the factorial of a number using recursion
if n == 0:
return 1
else:
return n * factorial(n-1)
def shuffle_list(data_list):
# Shuffle a list in-place using the Fisher-Yates shuffle algorithm
for i in range(len(data_list) - 1, 0, -1):
j = random.randint(0, i)
data_list[i], data_list[j] = data_list[j], data_list[i]
return generate_unique_id, insert_sorted, find_max_heap, run_length_encode, calculate_hcf, factorial, shuffle_list