function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def __init__(self, value: T) -> None: self._value: T = value self.left: RandomizedHeapNode[T] | None = None self.right: RandomizedHeapNode[T] | None = None
data_structures
def value(self) -> T: if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 if random.choice([True, False]): root1.left, root1.right = root1.right, root1.left root1.left = RandomizedHeapNode.merge(root1.left, root2) return root1
data_structures
def __init__(self, data: Iterable[T] | None = ()) -> None: self._root: RandomizedHeapNode[T] | None = None if data: for item in data: self.insert(item)
data_structures
def insert(self, value: T) -> None: self._root = RandomizedHeapNode.merge(self._root, RandomizedHeapNode(value))
data_structures
def pop(self) -> T | None: result = self.top() if self._root is None: return None self._root = RandomizedHeapNode.merge(self._root.left, self._root.right) return result
data_structures
def top(self) -> T: if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value
data_structures
def clear(self) -> None: self._root = None
data_structures
def to_sorted_list(self) -> list[Any]: result = [] while self: result.append(self.pop()) return result
data_structures
def __bool__(self) -> bool: return self._root is not None
data_structures
def __init__(self, val): self.val = val # Number of nodes in left subtree self.left_tree_size = 0 self.left = None self.right = None self.parent = None
data_structures
def merge_trees(self, other): assert self.left_tree_size == other.left_tree_size, "Unequal Sizes of Blocks" if self.val < other.val: other.left = self.right other.parent = None if self.right: self.right.parent = other self.right = other self.left_tree_size = self.left_tree_size * 2 + 1 return self else: self.left = other.right self.parent = None if other.right: other.right.parent = self other.right = self other.left_tree_size = other.left_tree_size * 2 + 1 return other
data_structures
def __init__(self, bottom_root=None, min_node=None, heap_size=0): self.size = heap_size self.bottom_root = bottom_root self.min_node = min_node
data_structures
def merge_heaps(self, other): # Empty heaps corner cases if other.size == 0: return None if self.size == 0: self.size = other.size self.bottom_root = other.bottom_root self.min_node = other.min_node return None # Update size self.size = self.size + other.size # Update min.node if self.min_node.val > other.min_node.val: self.min_node = other.min_node # Merge # Order roots by left_subtree_size combined_roots_list = [] i, j = self.bottom_root, other.bottom_root while i or j: if i and ((not j) or i.left_tree_size < j.left_tree_size): combined_roots_list.append((i, True)) i = i.parent else: combined_roots_list.append((j, False)) j = j.parent # Insert links between them for i in range(len(combined_roots_list) - 1): if combined_roots_list[i][1] != combined_roots_list[i + 1][1]: combined_roots_list[i][0].parent = combined_roots_list[i + 1][0] combined_roots_list[i + 1][0].left = combined_roots_list[i][0] # Consecutively merge roots with same left_tree_size i = combined_roots_list[0][0] while i.parent: if ( (i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent) ) or ( i.left_tree_size == i.parent.left_tree_size and i.left_tree_size != i.parent.parent.left_tree_size ): # Neighbouring Nodes previous_node = i.left next_node = i.parent.parent # Merging trees i = i.merge_trees(i.parent) # Updating links i.left = previous_node i.parent = next_node if previous_node: previous_node.parent = i if next_node: next_node.left = i else: i = i.parent # Updating self.bottom_root while i.left: i = i.left self.bottom_root = i # Update other other.size = self.size other.bottom_root = self.bottom_root other.min_node = self.min_node # Return the merged heap return self
data_structures
def insert(self, val): if self.size == 0: self.bottom_root = Node(val) self.size = 1 self.min_node = self.bottom_root else: # Create new node new_node = Node(val) # Update size self.size += 1 # update min_node if val < self.min_node.val: self.min_node = new_node # Put new_node as a bottom_root in heap self.bottom_root.left = new_node new_node.parent = self.bottom_root self.bottom_root = new_node # Consecutively merge roots with same left_tree_size while ( self.bottom_root.parent and self.bottom_root.left_tree_size == self.bottom_root.parent.left_tree_size ): # Next node next_node = self.bottom_root.parent.parent # Merge self.bottom_root = self.bottom_root.merge_trees(self.bottom_root.parent) # Update Links self.bottom_root.parent = next_node self.bottom_root.left = None if next_node: next_node.left = self.bottom_root
data_structures
def peek(self): return self.min_node.val
data_structures
def is_empty(self): return self.size == 0
data_structures
def delete_min(self): # assert not self.isEmpty(), "Empty Heap" # Save minimal value min_value = self.min_node.val # Last element in heap corner case if self.size == 1: # Update size self.size = 0 # Update bottom root self.bottom_root = None # Update min_node self.min_node = None return min_value # No right subtree corner case # The structure of the tree implies that this should be the bottom root # and there is at least one other root if self.min_node.right is None: # Update size self.size -= 1 # Update bottom root self.bottom_root = self.bottom_root.parent self.bottom_root.left = None # Update min_node self.min_node = self.bottom_root i = self.bottom_root.parent while i: if i.val < self.min_node.val: self.min_node = i i = i.parent return min_value # General case # Find the BinomialHeap of the right subtree of min_node bottom_of_new = self.min_node.right bottom_of_new.parent = None min_of_new = bottom_of_new size_of_new = 1 # Size, min_node and bottom_root while bottom_of_new.left: size_of_new = size_of_new * 2 + 1 bottom_of_new = bottom_of_new.left if bottom_of_new.val < min_of_new.val: min_of_new = bottom_of_new # Corner case of single root on top left path if (not self.min_node.left) and (not self.min_node.parent): self.size = size_of_new self.bottom_root = bottom_of_new self.min_node = min_of_new # print("Single root, multiple nodes case") return min_value # Remaining cases # Construct heap of right subtree new_heap = BinomialHeap( bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new ) # Update size self.size = self.size - 1 - size_of_new # Neighbour nodes previous_node = self.min_node.left next_node = self.min_node.parent # Initialize new bottom_root and min_node self.min_node = previous_node or next_node self.bottom_root = next_node # Update links of previous_node and search below for new min_node and # bottom_root if previous_node: previous_node.parent = next_node # Update bottom_root and search for min_node below self.bottom_root = previous_node self.min_node = previous_node while self.bottom_root.left: self.bottom_root = self.bottom_root.left if self.bottom_root.val < self.min_node.val: self.min_node = self.bottom_root if next_node: next_node.left = previous_node # Search for new min_node above min_node i = next_node while i: if i.val < self.min_node.val: self.min_node = i i = i.parent # Merge heaps self.merge_heaps(new_heap) return min_value
data_structures
def pre_order(self): # Find top root top_root = self.bottom_root while top_root.parent: top_root = top_root.parent # preorder heap_pre_order = [] self.__traversal(top_root, heap_pre_order) return heap_pre_order
data_structures
def __traversal(self, curr_node, preorder, level=0): if curr_node: preorder.append((curr_node.val, level)) self.__traversal(curr_node.left, preorder, level + 1) self.__traversal(curr_node.right, preorder, level + 1) else: preorder.append(("#", level))
data_structures
def __str__(self): if self.is_empty(): return "" preorder_heap = self.pre_order() return "\n".join(("-" * level + str(value)) for value, level in preorder_heap)
data_structures
def __init__(self): self.__heap = [0] self.__size = 0
data_structures
def __swap_up(self, i: int) -> None: self.__heap.append(value) self.__size += 1 self.__swap_up(self.__size)
data_structures
def __swap_down(self, i: int) -> None: max_value = self.__heap[1] self.__heap[1] = self.__heap[self.__size] self.__size -= 1 self.__heap.pop() self.__swap_down(1) return max_value
data_structures
def get_list(self): return self.__heap[1:]
data_structures
def permute(nums: list[int]) -> list[list[int]]: result = [] if len(nums) == 1: return [nums.copy()] for _ in range(len(nums)): n = nums.pop(0) permutations = permute(nums) for perm in permutations: perm.append(n) result.extend(permutations) nums.append(n) return result
data_structures
def __init__(self, array: list[int]) -> None: len_array = len(array) self.prefix_sum = [0] * len_array if len_array > 0: self.prefix_sum[0] = array[0] for i in range(1, len_array): self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i]
data_structures
def get_sum(self, start: int, end: int) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1]
data_structures
def contains_sum(self, target_sum: int) -> bool: sums = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(sum_item) return False
data_structures
def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur
data_structures
def __iter__(self) -> Deque._Iterator: return self
data_structures
def __next__(self) -> Any: if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next_node return val
data_structures
def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val)
data_structures
def append(self, val: Any) -> None: node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next_node = node node.prev_node = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value."
data_structures
def appendleft(self, val: Any) -> None: node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next_node = self._front self._front.prev_node = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value."
data_structures
def extend(self, iterable: Iterable[Any]) -> None: for val in iterable: self.append(val)
data_structures
def extendleft(self, iterable: Iterable[Any]) -> None: for val in iterable: self.appendleft(val)
data_structures
def pop(self) -> Any: # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back self._back = self._back.prev_node # set new back # drop the last node - python will deallocate memory automatically self._back.next_node = None self._len -= 1 return topop.val
data_structures
def popleft(self) -> Any: # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front self._front = self._front.next_node # set new front and drop the first node self._front.prev_node = None self._len -= 1 return topop.val
data_structures
def is_empty(self) -> bool: return self._front is None
data_structures
def __len__(self) -> int: return self._len
data_structures
def __eq__(self, other: object) -> bool: if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the dequeues are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next_node oth = oth.next_node return True
data_structures
def __iter__(self) -> Deque._Iterator: return Deque._Iterator(self._front)
data_structures
def __repr__(self) -> str: values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next_node return f"[{', '.join(repr(val) for val in values_list)}]"
data_structures
def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity)
data_structures
def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node
data_structures
def is_empty(self) -> bool: return ( self.front == self.rear and self.front is not None and self.front.data is None )
data_structures
def first(self) -> Any | None: self.check_can_perform_operation() return self.front.data if self.front else None
data_structures
def enqueue(self, data: Any) -> None: if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data
data_structures
def dequeue(self) -> Any: self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data
data_structures
def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue")
data_structures
def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue")
data_structures
def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None
data_structures
def __init__(self): self.queues = [ [], [], [], ]
data_structures
def enqueue(self, priority: int, data: int) -> None: try: if len(self.queues[priority]) >= 100: raise OverflowError("Maximum queue size is 100") self.queues[priority].append(data) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2")
data_structures
def dequeue(self) -> int: for queue in self.queues: if queue: return queue.pop(0) raise UnderFlowError("All queues are empty")
data_structures
def __str__(self) -> str: return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues))
data_structures
def __init__(self): self.queue = []
data_structures
def enqueue(self, data: int) -> None: if len(self.queue) == 100: raise OverFlowError("Maximum queue size is 100") self.queue.append(data)
data_structures
def dequeue(self) -> int: if not self.queue: raise UnderFlowError("The queue is empty") else: data = min(self.queue) self.queue.remove(data) return data
data_structures
def __str__(self) -> str: return str(self.queue)
data_structures
def fixed_priority_queue(): fpq = FixedPriorityQueue() fpq.enqueue(0, 10) fpq.enqueue(1, 70) fpq.enqueue(0, 100) fpq.enqueue(2, 1) fpq.enqueue(2, 5) fpq.enqueue(1, 7) fpq.enqueue(2, 4) fpq.enqueue(1, 64) fpq.enqueue(0, 128) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue())
data_structures
def element_priority_queue(): epq = ElementPriorityQueue() epq.enqueue(10) epq.enqueue(70) epq.enqueue(100) epq.enqueue(1) epq.enqueue(5) epq.enqueue(7) epq.enqueue(4) epq.enqueue(64) epq.enqueue(128) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue())
data_structures
def __init__(self, data: bytes) -> None: self.data = data # Initialize hash values self.hashes = [ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, ] # Initialize round constants self.round_constants = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, ] self.preprocessed_data = self.preprocessing(self.data) self.final_hash()
hashes
def preprocessing(data: bytes) -> bytes: padding = b"\x80" + (b"\x00" * (63 - (len(data) + 8) % 64)) big_endian_integer = struct.pack(">Q", (len(data) * 8)) return data + padding + big_endian_integer
hashes
def final_hash(self) -> None: # Convert into blocks of 64 bytes self.blocks = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data), 64) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers words = list(struct.unpack(">16L", block)) # add 48 0-ed integers words += [0] * 48 a, b, c, d, e, f, g, h = self.hashes for index in range(0, 64): if index > 15: # modify the zero-ed indexes at the end of the array s0 = ( self.ror(words[index - 15], 7) ^ self.ror(words[index - 15], 18) ^ (words[index - 15] >> 3) ) s1 = ( self.ror(words[index - 2], 17) ^ self.ror(words[index - 2], 19) ^ (words[index - 2] >> 10) ) words[index] = ( words[index - 16] + s0 + words[index - 7] + s1 ) % 0x100000000 # Compression s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25) ch = (e & f) ^ ((~e & (0xFFFFFFFF)) & g) temp1 = ( h + s1 + ch + self.round_constants[index] + words[index] ) % 0x100000000 s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22) maj = (a & b) ^ (a & c) ^ (b & c) temp2 = (s0 + maj) % 0x100000000 h, g, f, e, d, c, b, a = ( g, f, e, ((d + temp1) % 0x100000000), c, b, a, ((temp1 + temp2) % 0x100000000), ) mutated_hash_values = [a, b, c, d, e, f, g, h] # Modify final values self.hashes = [ ((element + mutated_hash_values[index]) % 0x100000000) for index, element in enumerate(self.hashes) ] self.hash = "".join([hex(value)[2:].zfill(8) for value in self.hashes])
hashes
def ror(self, value: int, rotations: int) -> int: return 0xFFFFFFFF & (value << (32 - rotations)) | (value >> rotations)
hashes
def test_match_hashes(self) -> None: import hashlib msg = bytes("Test String", "utf-8") self.assertEqual(SHA256(msg).hash, hashlib.sha256(msg).hexdigest())
hashes
def main() -> None: # unittest.main() import doctest doctest.testmod() parser = argparse.ArgumentParser() parser.add_argument( "-s", "--string", dest="input_string", default="Hello World!! Welcome to Cryptography", help="Hash the string", ) parser.add_argument( "-f", "--file", dest="input_file", help="Hash contents of a file" ) args = parser.parse_args() input_string = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file, "rb") as f: hash_input = f.read() else: hash_input = bytes(input_string, "utf-8") print(SHA256(hash_input).hash)
hashes
def __init__(self, data): self.data = data self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
hashes
def rotate(n, b): return ((n << b) | (n >> (32 - b))) & 0xFFFFFFFF
hashes
def padding(self): padding = b"\x80" + b"\x00" * (63 - (len(self.data) + 8) % 64) padded_data = self.data + padding + struct.pack(">Q", 8 * len(self.data)) return padded_data
hashes
def split_blocks(self): return [ self.padded_data[i : i + 64] for i in range(0, len(self.padded_data), 64) ]
hashes
def expand_block(self, block): w = list(struct.unpack(">16L", block)) + [0] * 64 for i in range(16, 80): w[i] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1) return w
hashes
def final_hash(self): self.padded_data = self.padding() self.blocks = self.split_blocks() for block in self.blocks: expanded_block = self.expand_block(block) a, b, c, d, e = self.h for i in range(0, 80): if 0 <= i < 20: f = (b & c) | ((~b) & d) k = 0x5A827999 elif 20 <= i < 40: f = b ^ c ^ d k = 0x6ED9EBA1 elif 40 <= i < 60: f = (b & c) | (b & d) | (c & d) k = 0x8F1BBCDC elif 60 <= i < 80: f = b ^ c ^ d k = 0xCA62C1D6 a, b, c, d, e = ( self.rotate(a, 5) + f + e + k + expanded_block[i] & 0xFFFFFFFF, a, self.rotate(b, 30), c, d, ) self.h = ( self.h[0] + a & 0xFFFFFFFF, self.h[1] + b & 0xFFFFFFFF, self.h[2] + c & 0xFFFFFFFF, self.h[3] + d & 0xFFFFFFFF, self.h[4] + e & 0xFFFFFFFF, ) return "%08x%08x%08x%08x%08x" % tuple(self.h)
hashes
def testMatchHashes(self): # noqa: N802 msg = bytes("Test String", "utf-8") self.assertEqual(SHA1Hash(msg).final_hash(), hashlib.sha1(msg).hexdigest())
hashes
def main(): # unittest.main() parser = argparse.ArgumentParser(description="Process some strings or files") parser.add_argument( "--string", dest="input_string", default="Hello World!! Welcome to Cryptography", help="Hash the string", ) parser.add_argument("--file", dest="input_file", help="Hash contents of a file") args = parser.parse_args() input_string = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file, "rb") as f: hash_input = f.read() else: hash_input = bytes(input_string, "utf-8") print(SHA1Hash(hash_input).final_hash())
hashes
def rotator(): global gear_one_pos global gear_two_pos global gear_three_pos i = gear_one[0] gear_one.append(i) del gear_one[0] gear_one_pos += 1 if gear_one_pos % int(len(alphabets)) == 0: i = gear_two[0] gear_two.append(i) del gear_two[0] gear_two_pos += 1 if gear_two_pos % int(len(alphabets)) == 0: i = gear_three[0] gear_three.append(i) del gear_three[0] gear_three_pos += 1
hashes
def engine(input_character): target = alphabets.index(input_character) target = gear_one[target] target = gear_two[target] target = gear_three[target] target = reflector[target] target = gear_three.index(target) target = gear_two.index(target) target = gear_one.index(target) code.append(alphabets[target]) rotator()
hashes
def elf_hash(data: str) -> int: hash_ = x = 0 for letter in data: hash_ = (hash_ << 4) + ord(letter) x = hash_ & 0xF0000000 if x != 0: hash_ ^= x >> 24 hash_ &= ~x return hash_
hashes
def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8))
hashes
def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0"
hashes
def emitter_converter(size_par, data): if size_par + len(data) <= 2**size_par - (len(data) - 1): raise ValueError("size of parity don't match with size of data") data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)] # sorted information data for the size of the output data data_ord = [] # data position template + parity data_out_gab = [] # parity bit counter qtd_bp = 0 # counter position of data bits cont_data = 0 for x in range(1, size_par + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par: if (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a given parity cont_bo = 0 # counter to control the loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(cont_bo % 2) qtd_bp += 1 # Mount the message cont_bp = 0 # parity bit counter for x in range(0, size_par + len(data)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) return data_out
hashes
def receptor_converter(size_par, data): # data position template + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 # list of parity received parity_received = [] data_output = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_output.append(data[cont_data]) else: parity_received.append(data[cont_data]) cont_data += 1 # -----------calculates the parity with the data data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)] # sorted information data for the size of the output data data_ord = [] # Data position feedback + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 for x in range(1, size_par + len(data_output) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data_output[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a certain parity cont_bo = 0 # Counter to control loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(str(cont_bo % 2)) qtd_bp += 1 # Mount the message cont_bp = 0 # Parity bit counter for x in range(0, size_par + len(data_output)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) ack = parity_received == parity return data_output, ack
hashes
def rearrange(bit_string_32): if len(bit_string_32) != 32: raise ValueError("Need length 32") new_string = "" for i in [3, 2, 1, 0]: new_string += bit_string_32[8 * i : 8 * i + 8] return new_string
hashes
def reformat_hex(i): hexrep = format(i, "08x") thing = "" for i in [3, 2, 1, 0]: thing += hexrep[2 * i : 2 * i + 2] return thing
hashes
def pad(bit_string): start_length = len(bit_string) bit_string += "1" while len(bit_string) % 512 != 448: bit_string += "0" last_part = format(start_length, "064b") bit_string += rearrange(last_part[32:]) + rearrange(last_part[:32]) return bit_string
hashes
def get_block(bit_string): curr_pos = 0 while curr_pos < len(bit_string): curr_part = bit_string[curr_pos : curr_pos + 512] my_splits = [] for i in range(16): my_splits.append(int(rearrange(curr_part[32 * i : 32 * i + 32]), 2)) yield my_splits curr_pos += 512
hashes
def not32(i): i_str = format(i, "032b") new_str = "" for c in i_str: new_str += "1" if c == "0" else "0" return int(new_str, 2)
hashes
def sum32(a, b): return (a + b) % 2**32
hashes
def leftrot32(i, s): return (i << s) ^ (i >> (32 - s))
hashes
def md5me(test_string): bs = "" for i in test_string: bs += format(ord(i), "08b") bs = pad(bs) tvals = [int(2**32 * abs(math.sin(i + 1))) for i in range(64)] a0 = 0x67452301 b0 = 0xEFCDAB89 c0 = 0x98BADCFE d0 = 0x10325476 s = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] for m in get_block(bs): a = a0 b = b0 c = c0 d = d0 for i in range(64): if i <= 15: # f = (B & C) | (not32(B) & D) f = d ^ (b & (c ^ d)) g = i elif i <= 31: # f = (D & B) | (not32(D) & C) f = c ^ (d & (b ^ c)) g = (5 * i + 1) % 16 elif i <= 47: f = b ^ c ^ d g = (3 * i + 5) % 16 else: f = c ^ (b | not32(d)) g = (7 * i) % 16 dtemp = d d = c c = b b = sum32(b, leftrot32((a + f + tvals[i] + m[g]) % 2**32, s[i])) a = dtemp a0 = sum32(a0, a) b0 = sum32(b0, b) c0 = sum32(c0, c) d0 = sum32(d0, d) digest = reformat_hex(a0) + reformat_hex(b0) + reformat_hex(c0) + reformat_hex(d0) return digest
hashes
def test(): assert md5me("") == "d41d8cd98f00b204e9800998ecf8427e" assert ( md5me("The quick brown fox jumps over the lazy dog") == "9e107d9d372bb6826bd81d3542a419d6" ) print("Success.")
hashes
def indian_phone_validator(phone: str) -> bool: pat = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$") if match := re.search(pat, phone): return match.string == phone return False
strings
def z_function(input_str: str) -> list[int]: z_result = [0 for i in range(len(input_str))] # initialize interval's left pointer and right pointer left_pointer, right_pointer = 0, 0 for i in range(1, len(input_str)): # case when current index is inside the interval if i <= right_pointer: min_edge = min(right_pointer - i + 1, z_result[i - left_pointer]) z_result[i] = min_edge while go_next(i, z_result, input_str): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: left_pointer, right_pointer = i, i + z_result[i] - 1 return z_result
strings
def go_next(i: int, z_result: list[int], s: str) -> bool: return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]]
strings
def find_pattern(pattern: str, input_str: str) -> int: answer = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string z_result = z_function(pattern + input_str) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(pattern): answer += 1 return answer
strings
def remove_duplicates(sentence: str) -> str: return " ".join(sorted(set(sentence.split())))
strings
def create_ngram(sentence: str, ngram_size: int) -> list[str]: return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 1)]
strings
def is_palindrome(s: str) -> bool: start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True
strings
def is_palindrome_recursive(s: str) -> bool: if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False
strings