Description
stringlengths
18
161k
Code
stringlengths
15
300k
printshowbits0 0xffff 0 00000000 65535 1111111111111111 1 we use bitwise and operations to separate the even bits 0 2 4 6 etc and odd bits 1 3 5 7 etc in the input number 2 we then rightshift the even bits by 1 position and leftshift the odd bits by 1 position to swap them 3 finally we combine the swapped even and odd bits using a bitwise or operation to obtain the final result printshowbits0 swapoddevenbits0 0 00000000 0 00000000 printshowbits1 swapoddevenbits1 1 00000001 2 00000010 printshowbits2 swapoddevenbits2 2 00000010 1 00000001 printshowbits3 swapoddevenbits3 3 00000011 3 00000011 printshowbits4 swapoddevenbits4 4 00000100 8 00001000 printshowbits5 swapoddevenbits5 5 00000101 10 00001010 printshowbits6 swapoddevenbits6 6 00000110 9 00001001 printshowbits23 swapoddevenbits23 23 00010111 43 00101011 get all even bits 0xaaaaaaaa is a 32bit number with all even bits set to 1 get all odd bits 0x55555555 is a 32bit number with all odd bits set to 1 right shift even bits and left shift odd bits and swap them print show_bits 0 0xffff 0 00000000 65535 1111111111111111 1 we use bitwise and operations to separate the even bits 0 2 4 6 etc and odd bits 1 3 5 7 etc in the input number 2 we then right shift the even bits by 1 position and left shift the odd bits by 1 position to swap them 3 finally we combine the swapped even and odd bits using a bitwise or operation to obtain the final result print show_bits 0 swap_odd_even_bits 0 0 00000000 0 00000000 print show_bits 1 swap_odd_even_bits 1 1 00000001 2 00000010 print show_bits 2 swap_odd_even_bits 2 2 00000010 1 00000001 print show_bits 3 swap_odd_even_bits 3 3 00000011 3 00000011 print show_bits 4 swap_odd_even_bits 4 4 00000100 8 00001000 print show_bits 5 swap_odd_even_bits 5 5 00000101 10 00001010 print show_bits 6 swap_odd_even_bits 6 6 00000110 9 00001001 print show_bits 23 swap_odd_even_bits 23 23 00010111 43 00101011 get all even bits 0xaaaaaaaa is a 32 bit number with all even bits set to 1 get all odd bits 0x55555555 is a 32 bit number with all odd bits set to 1 right shift even bits and left shift odd bits and swap them
def show_bits(before: int, after: int) -> str: return f"{before:>5}: {before:08b}\n{after:>5}: {after:08b}" def swap_odd_even_bits(num: int) -> int: even_bits = num & 0xAAAAAAAA odd_bits = num & 0x55555555 return even_bits >> 1 | odd_bits << 1 if __name__ == "__main__": import doctest doctest.testmod() for i in (-1, 0, 1, 2, 3, 4, 23, 24): print(show_bits(i, swap_odd_even_bits(i)), "\n")
diophantine equation given integers a b c at least one of a and b 0 the diophantine equation ax by c has a solution where x and y are integers iff greatestcommondivisora b divides c gcd greatest common divisor or hcf highest common factor diophantine10 6 14 7 0 14 0 diophantine391 299 69 9 0 12 0 but above equation has one more solution i e x 4 y 5 that s why we need diophantine all solution function lemma if nab and gcda n 1 then nb finding all solutions of diophantine equations theorem let gcda b d a dp b dq if x0 y0 is a solution of diophantine equation ax by c ax0 by0 c then all the solutions have the form ax0 tq by0 tp c where t is an arbitrary integer n is the number of solution you want n 2 by default diophantineallsoln10 6 14 7 0 14 0 4 0 9 0 diophantineallsoln10 6 14 4 7 0 14 0 4 0 9 0 1 0 4 0 2 0 1 0 diophantineallsoln391 299 69 n 4 9 0 12 0 22 0 29 0 35 0 46 0 48 0 63 0 extended euclid s algorithm if d divides a and b and d ax by for integers x and y then d gcda b extendedgcd10 6 2 1 2 extendedgcd7 5 1 2 3 diophantine equation given integers a b c at least one of a and b 0 the diophantine equation a x b y c has a solution where x and y are integers iff greatest_common_divisor a b divides c gcd greatest common divisor or hcf highest common factor diophantine 10 6 14 7 0 14 0 diophantine 391 299 69 9 0 12 0 but above equation has one more solution i e x 4 y 5 that s why we need diophantine all solution function greatest_common_divisor a b is in maths directory extended_gcd a b function implemented below lemma if n ab and gcd a n 1 then n b finding all solutions of diophantine equations theorem let gcd a b d a d p b d q if x0 y0 is a solution of diophantine equation a x b y c a x0 b y0 c then all the solutions have the form a x0 t q b y0 t p c where t is an arbitrary integer n is the number of solution you want n 2 by default diophantine_all_soln 10 6 14 7 0 14 0 4 0 9 0 diophantine_all_soln 10 6 14 4 7 0 14 0 4 0 9 0 1 0 4 0 2 0 1 0 diophantine_all_soln 391 299 69 n 4 9 0 12 0 22 0 29 0 35 0 46 0 48 0 63 0 initial value extended euclid s algorithm if d divides a and b and d a x b y for integers x and y then d gcd a b extended_gcd 10 6 2 1 2 extended_gcd 7 5 1 2 3
from __future__ import annotations from maths.greatest_common_divisor import greatest_common_divisor def diophantine(a: int, b: int, c: int) -> tuple[float, float]: assert ( c % greatest_common_divisor(a, b) == 0 ) (d, x, y) = extended_gcd(a, b) r = c / d return (r * x, r * y) def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: (x0, y0) = diophantine(a, b, c) d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y) def extended_gcd(a: int, b: int) -> tuple[int, int, int]: assert a >= 0 assert b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 assert b % d == 0 assert d == a * x + b * y return (d, x, y) if __name__ == "__main__": from doctest import testmod testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
an and gate is a logic gate in boolean algebra which results to 1 true if both the inputs are 1 and 0 false otherwise following is the truth table of an and gate input 1 input 2 output 0 0 0 0 1 0 1 0 0 1 1 1 refer https www geeksforgeeks orglogicgatesinpython calculate and of the input values andgate0 0 0 andgate0 1 0 andgate1 0 0 andgate1 1 1 calculate and of the input values and_gate 0 0 0 and_gate 0 1 0 and_gate 1 0 0 and_gate 1 1 1
def and_gate(input_1: int, input_2: int) -> int: return int(input_1 and input_2) if __name__ == "__main__": import doctest doctest.testmod()
an imply gate is a logic gate in boolean algebra which results to 1 if either input 1 is 0 or if input 1 is 1 then the output is 1 only if input 2 is 1 it is true if input 1 implies input 2 following is the truth table of an imply gate input 1 input 2 output 0 0 1 0 1 1 1 0 0 1 1 1 refer https en wikipedia orgwikiimplygate calculate imply of the input values implygate0 0 1 implygate0 1 1 implygate1 0 0 implygate1 1 1 calculate imply of the input values imply_gate 0 0 1 imply_gate 0 1 1 imply_gate 1 0 0 imply_gate 1 1 1
def imply_gate(input_1: int, input_2: int) -> int: return int(input_1 == 0 or input_2 == 1) if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikikarnaughmap https www allaboutcircuits comtechnicalarticleskarnaughmapbooleanalgebraicsimplificationtechnique simplify the karnaugh map simplifykmapkmap0 1 1 1 a b ab ab simplifykmapkmap0 0 0 0 simplifykmapkmap0 1 1 1 a b ab ab simplifykmapkmap0 1 1 2 a b ab ab simplifykmapkmap0 1 1 1 1 a b ab ab simplifykmapkmap0 1 1 a a b ab ab main function to create and simplify a kmap main 0 1 1 1 simplified expression a b ab ab manually generate the product of 0 1 and 0 1 simplify the karnaugh map simplify_kmap kmap 0 1 1 1 a b ab ab simplify_kmap kmap 0 0 0 0 simplify_kmap kmap 0 1 1 1 a b ab ab simplify_kmap kmap 0 1 1 2 a b ab ab simplify_kmap kmap 0 1 1 1 1 a b ab ab simplify_kmap kmap 0 1 1 a a b ab ab main function to create and simplify a k map main 0 1 1 1 simplified expression a b ab ab manually generate the product of 0 1 and 0 1
def simplify_kmap(kmap: list[list[int]]) -> str: simplified_f = [] for a, row in enumerate(kmap): for b, item in enumerate(row): if item: term = ("A" if a else "A'") + ("B" if b else "B'") simplified_f.append(term) return " + ".join(simplified_f) def main() -> None: kmap = [[0, 1], [1, 1]] for row in kmap: print(row) print("Simplified Expression:") print(simplify_kmap(kmap)) if __name__ == "__main__": main() print(f"{simplify_kmap(kmap=[[0, 1], [1, 1]]) = }")
implement a 2to1 multiplexer param input0 the first input value 0 or 1 param input1 the second input value 0 or 1 param select the select signal 0 or 1 to choose between input0 and input1 return the output based on the select signal input1 if select else input0 https www electrically4u comsolvedproblemsonmultiplexer https en wikipedia orgwikimultiplexer mux0 1 0 0 mux0 1 1 1 mux1 0 0 1 mux1 0 1 0 mux2 1 0 traceback most recent call last valueerror inputs and select signal must be 0 or 1 mux0 1 0 traceback most recent call last valueerror inputs and select signal must be 0 or 1 mux0 1 1 1 traceback most recent call last valueerror inputs and select signal must be 0 or 1 implement a 2 to 1 multiplexer param input0 the first input value 0 or 1 param input1 the second input value 0 or 1 param select the select signal 0 or 1 to choose between input0 and input1 return the output based on the select signal input1 if select else input0 https www electrically4u com solved problems on multiplexer https en wikipedia org wiki multiplexer mux 0 1 0 0 mux 0 1 1 1 mux 1 0 0 1 mux 1 0 1 0 mux 2 1 0 traceback most recent call last valueerror inputs and select signal must be 0 or 1 mux 0 1 0 traceback most recent call last valueerror inputs and select signal must be 0 or 1 mux 0 1 1 1 traceback most recent call last valueerror inputs and select signal must be 0 or 1
def mux(input0: int, input1: int, select: int) -> int: if all(i in (0, 1) for i in (input0, input1, select)): return input1 if select else input0 raise ValueError("Inputs and select signal must be 0 or 1") if __name__ == "__main__": import doctest doctest.testmod()
a nand gate is a logic gate in boolean algebra which results to 0 false if both the inputs are 1 and 1 true otherwise it s similar to adding a not gate along with an and gate following is the truth table of a nand gate input 1 input 2 output 0 0 1 0 1 1 1 0 1 1 1 0 refer https www geeksforgeeks orglogicgatesinpython calculate nand of the input values nandgate0 0 1 nandgate0 1 1 nandgate1 0 1 nandgate1 1 0 calculate nand of the input values nand_gate 0 0 1 nand_gate 0 1 1 nand_gate 1 0 1 nand_gate 1 1 0
def nand_gate(input_1: int, input_2: int) -> int: return int(not (input_1 and input_2)) if __name__ == "__main__": import doctest doctest.testmod()
an nimply gate is a logic gate in boolean algebra which results to 0 if either input 1 is 0 or if input 1 is 1 then it is 0 only if input 2 is 1 it is false if input 1 implies input 2 it is the negated form of imply following is the truth table of an nimply gate input 1 input 2 output 0 0 0 0 1 0 1 0 1 1 1 0 refer https en wikipedia orgwikinimplygate calculate nimply of the input values nimplygate0 0 0 nimplygate0 1 0 nimplygate1 0 1 nimplygate1 1 0 calculate nimply of the input values nimply_gate 0 0 0 nimply_gate 0 1 0 nimply_gate 1 0 1 nimply_gate 1 1 0
def nimply_gate(input_1: int, input_2: int) -> int: return int(input_1 == 1 and input_2 == 0) if __name__ == "__main__": import doctest doctest.testmod()
a nor gate is a logic gate in boolean algebra which results in false0 if any of the inputs is 1 and true1 if all inputs are 0 following is the truth table of a nor gate truth table of nor gate input 1 input 2 output 0 0 1 0 1 0 1 0 0 1 1 0 code provided by akshaj vishwanathan https www geeksforgeeks orglogicgatesinpython norgate0 0 1 norgate0 1 0 norgate1 0 0 norgate1 1 0 norgate0 0 0 0 1 norgate0 7 0 printtruthtablenorgate truth table of nor gate input 1 input 2 output 0 0 1 0 1 0 1 0 0 1 1 0 maketablerowone two three one two three nor_gate 0 0 1 nor_gate 0 1 0 nor_gate 1 0 0 nor_gate 1 1 0 nor_gate 0 0 0 0 1 nor_gate 0 7 0 print truth_table nor_gate truth table of nor gate input 1 input 2 output 0 0 1 0 1 0 1 0 0 1 1 0 make_table_row one two three one two three
from collections.abc import Callable def nor_gate(input_1: int, input_2: int) -> int: return int(input_1 == input_2 == 0) def truth_table(func: Callable) -> str: def make_table_row(items: list | tuple) -> str: return f"| {' | '.join(f'{item:^8}' for item in items)} |" return "\n".join( ( "Truth Table of NOR Gate:", make_table_row(("Input 1", "Input 2", "Output")), *[make_table_row((i, j, func(i, j))) for i in (0, 1) for j in (0, 1)], ) ) if __name__ == "__main__": import doctest doctest.testmod() print(truth_table(nor_gate))
a not gate is a logic gate in boolean algebra which results to 0 false if the input is high and 1 true if the input is low following is the truth table of a xor gate input output 0 1 1 0 refer https www geeksforgeeks orglogicgatesinpython calculate not of the input values notgate0 1 notgate1 0 calculate not of the input values not_gate 0 1 not_gate 1 0
def not_gate(input_1: int) -> int: return 1 if input_1 == 0 else 0 if __name__ == "__main__": import doctest doctest.testmod()
an or gate is a logic gate in boolean algebra which results to 0 false if both the inputs are 0 and 1 true otherwise following is the truth table of an and gate input 1 input 2 output 0 0 0 0 1 1 1 0 1 1 1 1 refer https www geeksforgeeks orglogicgatesinpython calculate or of the input values orgate0 0 0 orgate0 1 1 orgate1 0 1 orgate1 1 1 calculate or of the input values or_gate 0 0 0 or_gate 0 1 1 or_gate 1 0 1 or_gate 1 1 1
def or_gate(input_1: int, input_2: int) -> int: return int((input_1, input_2).count(1) != 0) if __name__ == "__main__": import doctest doctest.testmod()
comparestring 0010 0110 010 comparestring 0110 1101 false check 0 00 01 5 0 00 01 5 decimaltobinary3 1 5 0 00 01 5 isfortable 1 011 2 true isfortable 01 001 1 false selection1 0 00 01 5 0 00 01 5 selection1 0 00 01 5 0 00 01 5 primeimplicantchart 0 00 01 5 0 00 01 5 1 compare_string 0010 0110 0_10 compare_string 0110 1101 false check 0 00 01 5 0 00 01 5 decimal_to_binary 3 1 5 0 00 01 5 is_for_table __1 011 2 true is_for_table 01_ 001 1 false selection 1 0 00 01 5 0 00 01 5 selection 1 0 00 01 5 0 00 01 5 prime_implicant_chart 0 00 01 5 0 00 01 5 1
from __future__ import annotations from collections.abc import Sequence from typing import Literal def compare_string(string1: str, string2: str) -> str | Literal[False]: list1 = list(string1) list2 = list(string2) count = 0 for i in range(len(list1)): if list1[i] != list2[i]: count += 1 list1[i] = "_" if count > 1: return False else: return "".join(list1) def check(binary: list[str]) -> list[str]: pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k is False: check1[i] = "*" check1[j] = "*" temp.append("X") for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: list1 = list(string1) list2 = list(string2) count_n = sum(item1 != item2 for item1, item2 in zip(list1, list2)) return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = sum(row[i] == 1 for row in chart) if count == 1: rem = max(j for j, row in enumerate(chart) if row[i] == 1) select[rem] = 1 for i, item in enumerate(select): if item != 1: continue for j in range(len(chart[0])): if chart[i][j] != 1: continue for row in chart: row[j] = 0 temp.append(prime_implicants[i]) while True: counts = [chart[i].count(1) for i in range(len(chart))] max_n = max(counts) rem = counts.index(max_n) if max_n == 0: return temp temp.append(prime_implicants[rem]) for j in range(len(chart[0])): if chart[rem][j] != 1: continue for i in range(len(chart)): chart[i][j] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
a xnor gate is a logic gate in boolean algebra which results to 0 false if both the inputs are different and 1 true if the inputs are same it s similar to adding a not gate to an xor gate following is the truth table of a xnor gate input 1 input 2 output 0 0 1 0 1 0 1 0 0 1 1 1 refer https www geeksforgeeks orglogicgatesinpython calculate xor of the input values xnorgate0 0 1 xnorgate0 1 0 xnorgate1 0 0 xnorgate1 1 1 calculate xor of the input values xnor_gate 0 0 1 xnor_gate 0 1 0 xnor_gate 1 0 0 xnor_gate 1 1 1
def xnor_gate(input_1: int, input_2: int) -> int: return 1 if input_1 == input_2 else 0 if __name__ == "__main__": import doctest doctest.testmod()
a xor gate is a logic gate in boolean algebra which results to 1 true if only one of the two inputs is 1 and 0 false if an even number of inputs are 1 following is the truth table of a xor gate input 1 input 2 output 0 0 0 0 1 1 1 0 1 1 1 0 refer https www geeksforgeeks orglogicgatesinpython calculate xor of the input values xorgate0 0 0 xorgate0 1 1 xorgate1 0 1 xorgate1 1 0 calculate xor of the input values xor_gate 0 0 0 xor_gate 0 1 1 xor_gate 1 0 1 xor_gate 1 1 0
def xor_gate(input_1: int, input_2: int) -> int: return (input_1, input_2).count(0) % 2 if __name__ == "__main__": import doctest doctest.testmod()
conway s game of life implemented in python https en wikipedia orgwikiconway27sgameoflife define glider example define blinker example generates the next generation for a given state of conway s game of life newgenerationblinker 0 0 0 1 1 1 0 0 0 get the number of live neighbours rules of the game of life excerpt from wikipedia 1 any live cell with two or three live neighbours survives 2 any dead cell with three live neighbours becomes a live cell 3 all other live cells die in the next generation similarly all other dead cells stay dead generates a list of images of subsequent game of life states create output image save cells to image save image define glider example define blinker example generates the next generation for a given state of conway s game of life new_generation blinker 0 0 0 1 1 1 0 0 0 get the number of live neighbours rules of the game of life excerpt from wikipedia 1 any live cell with two or three live neighbours survives 2 any dead cell with three live neighbours becomes a live cell 3 all other live cells die in the next generation similarly all other dead cells stay dead generates a list of images of subsequent game of life states create output image save cells to image save image
from __future__ import annotations from PIL import Image GLIDER = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def new_generation(cells: list[list[int]]) -> list[list[int]]: next_generation = [] for i in range(len(cells)): next_generation_row = [] for j in range(len(cells[i])): neighbour_count = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i]) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i]) - 1: neighbour_count += cells[i][j + 1] if i < len(cells) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(cells) - 1: neighbour_count += cells[i + 1][j] if i < len(cells) - 1 and j < len(cells[i]) - 1: neighbour_count += cells[i + 1][j + 1] alive = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1) else: next_generation_row.append(0) next_generation.append(next_generation_row) return next_generation def generate_images(cells: list[list[int]], frames: int) -> list[Image.Image]: images = [] for _ in range(frames): img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() for x in range(len(cells)): for y in range(len(cells[0])): colour = 255 - cells[y][x] * 255 pixels[x, y] = (colour, colour, colour) images.append(img) cells = new_generation(cells) return images if __name__ == "__main__": images = generate_images(GLIDER, 16) images[0].save("out.gif", save_all=True, append_images=images[1:])
conway s game of life anurag kumarmailto anuragkumarak95gmail com requirements numpy random time matplotlib python 3 5 usage python3 gameoflife canvassize int gameoflife rules 1 any live cell with fewer than two live neighbours dies as if caused by underpopulation 2 any live cell with two or three live neighbours lives on to the next generation 3 any live cell with more than three live neighbours dies as if by overpopulation 4 any dead cell with exactly three live neighbours be comes a live cell as if by reproduction this function runs the rules of game through all points and changes their status accordingly in the same canvas args canvas canvas of population to run the rules on returns canvas of population after one step finding dead or alive neighbours count handling duplicate entry for focus pt running the rules of game here main working structure of this module do nothing this function runs the rules of game through all points and changes their status accordingly in the same canvas args canvas canvas of population to run the rules on returns canvas of population after one step finding dead or alive neighbours count handling duplicate entry for focus pt running the rules of game here main working structure of this module do nothing
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap usage_doc = "Usage of script: script_name <size_of_canvas:int>" choice = [0] * 100 + [1] * 10 random.shuffle(choice) def create_canvas(size: int) -> list[list[bool]]: canvas = [[False for i in range(size)] for j in range(size)] return canvas def seed(canvas: list[list[bool]]) -> None: for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1)) def run(canvas: list[list[bool]]) -> list[list[bool]]: current_canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(current_canvas.shape[0])) for r, row in enumerate(current_canvas): for c, pt in enumerate(row): next_gen_canvas[r][c] = __judge_point( pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) return next_gen_canvas.tolist() def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool: dead = 0 alive = 0 for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 if pt: alive -= 1 else: dead -= 1 state = pt if pt: if alive < 2: state = False elif alive in {2, 3}: state = True elif alive > 3: state = False else: if alive == 3: state = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: pass
langton s ant https en wikipedia orgwikilangton27sant https upload wikimedia orgwikipediacommons009langtonsantanimated gif represents the main langonsant algorithm la langtonsant2 2 la board true true true true la antposition 1 1 each square is either true or false where true is white and false is black initially pointing left similar to the wikipedia image 0 0 1 90 2 180 3 270 performs three tasks 1 the ant turns either clockwise or anticlockwise according to the colour of the square that it is currently on if the square is white the ant turns clockwise and if the square is black the ant turns anticlockwise 2 the ant moves one square in the direction that it is currently facing 3 the square the ant was previously on is inverted white black and black white if display is true the board will also be displayed on the axes la langtonsant2 2 la moveantnone true 0 la board true true true false la moveantnone true 0 la board true false true false turn clockwise or anticlockwise according to colour of square the square is white so turn 90 clockwise the square is black so turn 90 anticlockwise move ant flip colour of square display the board on the axes displays the board without delay in a matplotlib plot to visually understand and track the ant langtonsantwidth height assign animation to a variable to prevent it from getting garbage collected represents the main langonsant algorithm la langtonsant 2 2 la board true true true true la ant_position 1 1 each square is either true or false where true is white and false is black initially pointing left similar to the wikipedia image 0 0 1 90 2 180 3 270 performs three tasks 1 the ant turns either clockwise or anti clockwise according to the colour of the square that it is currently on if the square is white the ant turns clockwise and if the square is black the ant turns anti clockwise 2 the ant moves one square in the direction that it is currently facing 3 the square the ant was previously on is inverted white black and black white if display is true the board will also be displayed on the axes la langtonsant 2 2 la move_ant none true 0 la board true true true false la move_ant none true 0 la board true false true false 0 90 180 270 turn clockwise or anti clockwise according to colour of square the square is white so turn 90 clockwise the square is black so turn 90 anti clockwise move ant flip colour of square display the board on the axes displays the board without delay in a matplotlib plot to visually understand and track the ant _ langtonsant width height assign animation to a variable to prevent it from getting garbage collected
from functools import partial from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation WIDTH = 80 HEIGHT = 80 class LangtonsAnt: def __init__(self, width: int, height: int) -> None: self.board = [[True] * width for _ in range(height)] self.ant_position: tuple[int, int] = (width // 2, height // 2) self.ant_direction: int = 3 def move_ant(self, axes: plt.Axes | None, display: bool, _frame: int) -> None: directions = { 0: (-1, 0), 1: (0, 1), 2: (1, 0), 3: (0, -1), } x, y = self.ant_position if self.board[x][y] is True: self.ant_direction = (self.ant_direction + 1) % 4 else: self.ant_direction = (self.ant_direction - 1) % 4 move_x, move_y = directions[self.ant_direction] self.ant_position = (x + move_x, y + move_y) self.board[x][y] = not self.board[x][y] if display and axes: axes.get_xaxis().set_ticks([]) axes.get_yaxis().set_ticks([]) axes.imshow(self.board, cmap="gray", interpolation="nearest") def display(self, frames: int = 100_000) -> None: fig, ax = plt.subplots() self.animation = FuncAnimation( fig, partial(self.move_ant, ax, True), frames=frames, interval=1 ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() LangtonsAnt(WIDTH, HEIGHT).display()
simulate the evolution of a highway with only one road that is a loop the highway is divided in cells each cell can have at most one car in it the highway is a loop so when a car comes to one end it will come out on the other each car is represented by its speed from 0 to 5 some information about speed 1 means that the cell on the highway is empty 0 to 5 are the speed of the cars with 0 being the lowest and 5 the highest highway listint where every position and speed of every car will be stored probability the probability that a driver will slow down initialspeed the speed of the cars a the start frequency how many cells there are between two cars at the start maxspeed the maximum speed a car can go to numberofcells how many cell are there in the highway numberofupdate how many times will the position be updated more information here https en wikipedia orgwikinagele28093schreckenbergmodel examples for doctest simulateconstructhighway6 3 0 2 0 2 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 simulateconstructhighway5 2 2 3 0 2 0 1 0 1 0 0 1 0 1 1 0 1 1 1 1 1 1 1 0 1 build the highway following the parameters given constructhighway10 2 6 6 1 6 1 6 1 6 1 6 1 constructhighway10 10 2 2 1 1 1 1 1 1 1 1 1 get the distance between a car at index carindex and the next car getdistance6 1 6 1 6 2 1 getdistance2 1 1 1 3 1 0 1 3 2 0 3 getdistance1 1 1 1 2 1 1 1 3 1 4 here if the car is near the end of the highway update the speed of the cars update1 1 1 1 1 2 1 1 1 1 3 0 0 5 1 1 1 1 1 3 1 1 1 1 4 update1 1 2 1 1 1 1 3 0 0 5 1 1 3 1 1 1 1 1 beforce calculations the highway is empty add 1 to the current speed of the car and cap the speed number of empty cell before the next car we can t have the car causing an accident randomly a driver will slow down the main function it will simulate the evolution of the highway simulate1 2 1 1 1 3 2 0 0 3 1 2 1 1 1 3 1 1 1 2 1 0 1 1 1 0 1 1 simulate1 2 1 3 4 0 0 3 1 2 1 3 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 change the position based on the speed with to create the loop commit the change of position build the highway following the parameters given construct_highway 10 2 6 6 1 6 1 6 1 6 1 6 1 construct_highway 10 10 2 2 1 1 1 1 1 1 1 1 1 create a highway without any car place the cars arbitrary number may need tuning get the distance between a car at index car_index and the next car get_distance 6 1 6 1 6 2 1 get_distance 2 1 1 1 3 1 0 1 3 2 0 3 get_distance 1 1 1 1 2 1 1 1 3 1 4 may need a better name for this if the cell is not empty then we have the distance we wanted here if the car is near the end of the highway update the speed of the cars update 1 1 1 1 1 2 1 1 1 1 3 0 0 5 1 1 1 1 1 3 1 1 1 1 4 update 1 1 2 1 1 1 1 3 0 0 5 1 1 3 1 1 1 1 1 beforce calculations the highway is empty add 1 to the current speed of the car and cap the speed number of empty cell before the next car we can t have the car causing an accident randomly a driver will slow down the main function it will simulate the evolution of the highway simulate 1 2 1 1 1 3 2 0 0 3 1 2 1 1 1 3 1 1 1 2 1 0 1 1 1 0 1 1 simulate 1 2 1 3 4 0 0 3 1 2 1 3 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 change the position based on the speed with to create the loop commit the change of position
from random import randint, random def construct_highway( number_of_cells: int, frequency: int, initial_speed: int, random_frequency: bool = False, random_speed: bool = False, max_speed: int = 5, ) -> list: highway = [[-1] * number_of_cells] i = 0 initial_speed = max(initial_speed, 0) while i < number_of_cells: highway[0][i] = ( randint(0, max_speed) if random_speed else initial_speed ) i += ( randint(1, max_speed * 2) if random_frequency else frequency ) return highway def get_distance(highway_now: list, car_index: int) -> int: distance = 0 cells = highway_now[car_index + 1 :] for cell in range(len(cells)): if cells[cell] != -1: return distance distance += 1 return distance + get_distance(highway_now, -1) def update(highway_now: list, probability: float, max_speed: int) -> list: number_of_cells = len(highway_now) next_highway = [-1] * number_of_cells for car_index in range(number_of_cells): if highway_now[car_index] != -1: next_highway[car_index] = min(highway_now[car_index] + 1, max_speed) dn = get_distance(highway_now, car_index) - 1 next_highway[car_index] = min(next_highway[car_index], dn) if random() < probability: next_highway[car_index] = max(next_highway[car_index] - 1, 0) return next_highway def simulate( highway: list, number_of_update: int, probability: float, max_speed: int ) -> list: number_of_cells = len(highway[0]) for i in range(number_of_update): next_speeds_calculated = update(highway[i], probability, max_speed) real_next_speeds = [-1] * number_of_cells for car_index in range(number_of_cells): speed = next_speeds_calculated[car_index] if speed != -1: index = (car_index + speed) % number_of_cells real_next_speeds[index] = speed highway.append(real_next_speeds) return highway if __name__ == "__main__": import doctest doctest.testmod()
return an image of 16 generations of onedimensional cellular automata based on a given ruleset number https mathworld wolfram comelementarycellularautomaton html define the first generation of cells fmt off fmt on formatruleset11100 0 0 0 1 1 1 0 0 formatruleset0 0 0 0 0 0 0 0 0 formatruleset11111111 1 1 1 1 1 1 1 1 get the neighbors of each cell handle neighbours outside bounds by using 0 as their value define a new cell and add it to the new generation convert the cells into a greyscale pil image image and return it to the caller from random import random cells random for w in range31 for h in range16 img generateimagecells isinstanceimg image image true img width img height 31 16 create the output image generates image uncomment to save the image img savefrulerulenum png define the first generation of cells fmt off fmt on format_ruleset 11100 0 0 0 1 1 1 0 0 format_ruleset 0 0 0 0 0 0 0 0 0 format_ruleset 11111111 1 1 1 1 1 1 1 1 31 get the neighbors of each cell handle neighbours outside bounds by using 0 as their value define a new cell and add it to the new generation convert the cells into a greyscale pil image image and return it to the caller from random import random cells random for w in range 31 for h in range 16 img generate_image cells isinstance img image image true img width img height 31 16 create the output image generates image uncomment to save the image img save f rule_ rule_num png
from __future__ import annotations from PIL import Image CELLS = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] def format_ruleset(ruleset: int) -> list[int]: return [int(c) for c in f"{ruleset:08}"[:8]] def new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]: population = len(cells[0]) next_generation = [] for i in range(population): left_neighbor = 0 if i == 0 else cells[time][i - 1] right_neighbor = 0 if i == population - 1 else cells[time][i + 1] situation = 7 - int(f"{left_neighbor}{cells[time][i]}{right_neighbor}", 2) next_generation.append(rule[situation]) return next_generation def generate_image(cells: list[list[int]]) -> Image.Image: img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() for w in range(img.width): for h in range(img.height): color = 255 - int(255 * cells[h][w]) pixels[w, h] = (color, color, color) return img if __name__ == "__main__": rule_num = bin(int(input("Rule:\n").strip()))[2:] rule = format_ruleset(int(rule_num)) for time in range(16): CELLS.append(new_generation(CELLS, rule, time)) img = generate_image(CELLS) img.show()
convert a string of characters to a sequence of numbers corresponding to the character s position in the alphabet https www dcode frletternumbercipher http bestcodes weebly coma1z26 html encodemyname 13 25 14 1 13 5 decode13 25 14 1 13 5 myname encode myname 13 25 14 1 13 5 decode 13 25 14 1 13 5 myname
from __future__ import annotations def encode(plain: str) -> list[int]: return [ord(elem) - 96 for elem in plain] def decode(encoded: list[int]) -> str: return "".join(chr(elem + 96) for elem in encoded) def main() -> None: encoded = encode(input("-> ").strip().lower()) print("Encoded: ", encoded) print("Decoded:", decode(encoded)) if __name__ == "__main__": main()
https en wikipedia orgwikiatbash import string def atbashslowsequence str str output for i in sequence extract ordi if 65 extract 90 output chr155 extract elif 97 extract 122 output chr219 extract else output i return output def atbashsequence str str letters string asciiletters lettersreversed string asciilowercase 1 string asciiuppercase 1 return join lettersreversedletters indexc if c in letters else c for c in sequence def benchmark none atbash_slow abcdefg zyxwvut atbash_slow aw 123bx zd 123yc atbash abcdefg zyxwvut atbash aw 123bx zd 123yc let s benchmark our functions side by side
import string def atbash_slow(sequence: str) -> str: output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= extract <= 122: output += chr(219 - extract) else: output += i return output def atbash(sequence: str) -> str: letters = string.ascii_letters letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(c)] if c in letters else c for c in sequence ) def benchmark() -> None: from timeit import timeit print("Running performance benchmarks...") setup = "from string import printable ; from __main__ import atbash, atbash_slow" print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds") print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds") if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
https en wikipedia orgwikiautokeycipher an autokey cipher also known as the autoclave cipher is a cipher that incorporates the message the plaintext into the key the key is generated from the message in some automated fashion sometimes by selecting certain letters from the text or more commonly by adding a short primer key to the front of the message encrypt a given plaintext string and key string returning the encrypted ciphertext encrypthello world coffee jsqqs avvwo encryptcoffee is good as python thealgorithms vvjfpk wj ohvp su ddylsv encryptcoffee is good as python 2 traceback most recent call last typeerror key must be a string encrypt thealgorithms traceback most recent call last valueerror plaintext is empty decrypt a given ciphertext string and key string returning the decrypted ciphertext decryptjsqqs avvwo coffee hello world decryptvvjfpk wj ohvp su ddylsv thealgorithms coffee is good as python decryptvvjfpk wj ohvp su ddylsv traceback most recent call last valueerror key is empty decrypt527 26 thealgorithms traceback most recent call last typeerror ciphertext must be a string encrypt a given plaintext string and key string returning the encrypted ciphertext encrypt hello world coffee jsqqs avvwo encrypt coffee is good as python thealgorithms vvjfpk wj ohvp su ddylsv encrypt coffee is good as python 2 traceback most recent call last typeerror key must be a string encrypt thealgorithms traceback most recent call last valueerror plaintext is empty decrypt a given ciphertext string and key string returning the decrypted ciphertext decrypt jsqqs avvwo coffee hello world decrypt vvjfpk wj ohvp su ddylsv thealgorithms coffee is good as python decrypt vvjfpk wj ohvp su ddylsv traceback most recent call last valueerror key is empty decrypt 527 26 thealgorithms traceback most recent call last typeerror ciphertext must be a string
def encrypt(plaintext: str, key: str) -> str: if not isinstance(plaintext, str): raise TypeError("plaintext must be a string") if not isinstance(key, str): raise TypeError("key must be a string") if not plaintext: raise ValueError("plaintext is empty") if not key: raise ValueError("key is empty") key += plaintext plaintext = plaintext.lower() key = key.lower() plaintext_iterator = 0 key_iterator = 0 ciphertext = "" while plaintext_iterator < len(plaintext): if ( ord(plaintext[plaintext_iterator]) < 97 or ord(plaintext[plaintext_iterator]) > 122 ): ciphertext += plaintext[plaintext_iterator] plaintext_iterator += 1 elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122: key_iterator += 1 else: ciphertext += chr( ( (ord(plaintext[plaintext_iterator]) - 97 + ord(key[key_iterator])) - 97 ) % 26 + 97 ) key_iterator += 1 plaintext_iterator += 1 return ciphertext def decrypt(ciphertext: str, key: str) -> str: if not isinstance(ciphertext, str): raise TypeError("ciphertext must be a string") if not isinstance(key, str): raise TypeError("key must be a string") if not ciphertext: raise ValueError("ciphertext is empty") if not key: raise ValueError("key is empty") key = key.lower() ciphertext_iterator = 0 key_iterator = 0 plaintext = "" while ciphertext_iterator < len(ciphertext): if ( ord(ciphertext[ciphertext_iterator]) < 97 or ord(ciphertext[ciphertext_iterator]) > 122 ): plaintext += ciphertext[ciphertext_iterator] else: plaintext += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key_iterator += 1 ciphertext_iterator += 1 return plaintext if __name__ == "__main__": import doctest doctest.testmod() operation = int(input("Type 1 to encrypt or 2 to decrypt:")) if operation == 1: plaintext = input("Typeplaintext to be encrypted:\n") key = input("Type the key:\n") print(encrypt(plaintext, key)) elif operation == 2: ciphertext = input("Type the ciphertext to be decrypted:\n") key = input("Type the key:\n") print(decrypt(ciphertext, key)) decrypt("jsqqs avvwo", "coffee")
program to encode and decode baconian or bacon s cipher wikipedia reference https en wikipedia orgwikibacon27scipher encodes to baconian cipher encodehello aabbbaabaaababaababaabbab encodehello world aabbbaabaaababaababaabbab babaaabbabbaaaaababaaaabb encodehello world traceback most recent call last exception encode accepts only letters of the alphabet and spaces decodes from baconian cipher decodeaabbbaabaaababaababaabbab babaaabbabbaaaaababaaaabb hello world decodeaabbbaabaaababaababaabbab hello decodeaabbbaabaaababaababaabbab babaaabbabbaaaaababaaaabb traceback most recent call last exception decode accepts only a b and spaces encodes to baconian cipher encode hello aabbbaabaaababaababaabbab encode hello world aabbbaabaaababaababaabbab babaaabbabbaaaaababaaaabb encode hello world traceback most recent call last exception encode accepts only letters of the alphabet and spaces decodes from baconian cipher decode aabbbaabaaababaababaabbab babaaabbabbaaaaababaaaabb hello world decode aabbbaabaaababaababaabbab hello decode aabbbaabaaababaababaabbab babaaabbabbaaaaababaaaabb traceback most recent call last exception decode accepts only a b and spaces
encode_dict = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "ABBAB", "p": "ABBBA", "q": "ABBBB", "r": "BAAAA", "s": "BAAAB", "t": "BAABA", "u": "BAABB", "v": "BBBAB", "w": "BABAA", "x": "BABAB", "y": "BABBA", "z": "BABBB", " ": " ", } decode_dict = {value: key for key, value in encode_dict.items()} def encode(word: str) -> str: encoded = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces") return encoded def decode(coded: str) -> str: if set(coded) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") decoded = "" for word in coded.split(): while len(word) != 0: decoded += decode_dict[word[:5]] word = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
encodes the given bytes into base16 base16encodeb hello world 48656c6c6f20576f726c6421 base16encodeb hello world 48454c4c4f20574f524c4421 base16encodeb turn the data into a list of integers where each integer is a byte then turn each byte into its hexadecimal representation make sure it is uppercase and then join everything together and return it decodes the given base16 encoded data into bytes base16decode 48656c6c6f20576f726c6421 b hello world base16decode 48454c4c4f20574f524c4421 b hello world base16decode b base16decode 486 traceback most recent call last valueerror base16 encoded data is invalid data does not have an even number of hex digits base16decode 48656c6c6f20576f726c6421 traceback most recent call last valueerror base16 encoded data is invalid data is not uppercase hex or it contains invalid characters base16decode this is not base64 encoded data traceback most recent call last valueerror base16 encoded data is invalid data is not uppercase hex or it contains invalid characters check data validity following rfc3548 https www ietf orgrfcrfc3548 txt base16 encoded data is invalid data does not have an even number of hex digits check the character set the standard base16 alphabet is uppercase according to rfc3548 section 6 if not setdata set0123456789abcdef raise valueerror for every two hexadecimal digits a byte turn it into an integer then string the result together into bytes and return it encodes the given bytes into base16 base16_encode b hello world 48656c6c6f20576f726c6421 base16_encode b hello world 48454c4c4f20574f524c4421 base16_encode b turn the data into a list of integers where each integer is a byte then turn each byte into its hexadecimal representation make sure it is uppercase and then join everything together and return it decodes the given base16 encoded data into bytes base16_decode 48656c6c6f20576f726c6421 b hello world base16_decode 48454c4c4f20574f524c4421 b hello world base16_decode b base16_decode 486 traceback most recent call last valueerror base16 encoded data is invalid data does not have an even number of hex digits base16_decode 48656c6c6f20576f726c6421 traceback most recent call last valueerror base16 encoded data is invalid data is not uppercase hex or it contains invalid characters base16_decode this is not base64 encoded data traceback most recent call last valueerror base16 encoded data is invalid data is not uppercase hex or it contains invalid characters check data validity following rfc3548 https www ietf org rfc rfc3548 txt base16 encoded data is invalid data does not have an even number of hex digits check the character set the standard base16 alphabet is uppercase according to rfc3548 section 6 base16 encoded data is invalid data is not uppercase hex or it contains invalid characters for every two hexadecimal digits a byte turn it into an integer then string the result together into bytes and return it
def base16_encode(data: bytes) -> str: return "".join([hex(byte)[2:].zfill(2).upper() for byte in list(data)]) def base16_decode(data: str) -> bytes: if (len(data) % 2) != 0: raise ValueError( ) if not set(data) <= set("0123456789ABCDEF"): raise ValueError( ) return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2)) if __name__ == "__main__": import doctest doctest.testmod()
base32 encoding and decoding https en wikipedia orgwikibase32 base32encodebhello world b jbswy3dpeblw64tmmqqq base32encodeb123456 b gezdgnbvgy base32encodebsome long complex string b onxw2zjanrxw4zzamnxw24dmmv4ca43uojuw4zy base32decodeb jbswy3dpeblw64tmmqqq b hello world base32decodeb gezdgnbvgy b 123456 base32decodeb onxw2zjanrxw4zzamnxw24dmmv4ca43uojuw4zy b some long complex string base32_encode b hello world b jbswy3dpeblw64tmmqqq base32_encode b 123456 b gezdgnbvgy base32_encode b some long complex string b onxw2zjanrxw4zzamnxw24dmmv4ca43uojuw4zy base32_decode b jbswy3dpeblw64tmmqqq b hello world base32_decode b gezdgnbvgy b 123456 base32_decode b onxw2zjanrxw4zzamnxw24dmmv4ca43uojuw4zy b some long complex string
B32_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" def base32_encode(data: bytes) -> bytes: binary_data = "".join(bin(ord(d))[2:].zfill(8) for d in data.decode("utf-8")) binary_data = binary_data.ljust(5 * ((len(binary_data) // 5) + 1), "0") b32_chunks = map("".join, zip(*[iter(binary_data)] * 5)) b32_result = "".join(B32_CHARSET[int(chunk, 2)] for chunk in b32_chunks) return bytes(b32_result.ljust(8 * ((len(b32_result) // 8) + 1), "="), "utf-8") def base32_decode(data: bytes) -> bytes: binary_chunks = "".join( bin(B32_CHARSET.index(_d))[2:].zfill(5) for _d in data.decode("utf-8").strip("=") ) binary_data = list(map("".join, zip(*[iter(binary_chunks)] * 8))) return bytes("".join([chr(int(_d, 2)) for _d in binary_data]), "utf-8") if __name__ == "__main__": import doctest doctest.testmod()
encodes data according to rfc4648 the data is first transformed to binary and appended with binary digits so that its length becomes a multiple of 6 then each 6 binary digits will match a character in the b64charset string the number of appended binary digits would later determine how many signs should be added the padding for every 2 binary digits added a sign is added in the output we can add any binary digits to make it a multiple of 6 for instance consider the following example aa 0010100100101001 001010 010010 1001 as can be seen above 2 more binary digits should be added so there s 4 possibilities here 00 01 10 or 11 that being said base64 encoding can be used in steganography to hide data in these appended digits from base64 import b64encode a bthis pull request is part of hacktoberfest20 b bhttps tools ietf orghtmlrfc4648 c ba base64encodea b64encodea true base64encodeb b64encodeb true base64encodec b64encodec true base64encodeabc traceback most recent call last typeerror a byteslike object is required not str make sure the supplied data is a byteslike object the padding that will be added later append binarystream with arbitrary binary digits 0 s by default to make its length a multiple of 6 encode every 6 binary digits to their corresponding base64 character decodes data according to rfc4648 this does the reverse operation of base64encode we first transform the encoded data back to a binary stream take off the previously appended binary digits according to the padding at this point we would have a binary stream whose length is multiple of 8 the last step is to convert every 8 bits to a byte from base64 import b64decode a vghpcybwdwxsihjlcxvlc3qgaxmgcgfydcbvzibiywnrdg9izxjmzxn0mjah b ahr0chm6ly90b29scy5pzxrmlm9yzy9odg1sl3jmyzq2ndg c qq base64decodea b64decodea true base64decodeb b64decodeb true base64decodec b64decodec true base64decodeabc traceback most recent call last assertionerror incorrect padding make sure encodeddata is either a string or a byteslike object in case encodeddata is a byteslike object make sure it contains only ascii characters so we convert it to a string object check if the encoded string contains non base64 characters check the padding remove padding if there is one encodes data according to rfc4648 the data is first transformed to binary and appended with binary digits so that its length becomes a multiple of 6 then each 6 binary digits will match a character in the b64_charset string the number of appended binary digits would later determine how many signs should be added the padding for every 2 binary digits added a sign is added in the output we can add any binary digits to make it a multiple of 6 for instance consider the following example aa 0010100100101001 001010 010010 1001 as can be seen above 2 more binary digits should be added so there s 4 possibilities here 00 01 10 or 11 that being said base64 encoding can be used in steganography to hide data in these appended digits from base64 import b64encode a b this pull request is part of hacktoberfest20 b b https tools ietf org html rfc4648 c b a base64_encode a b64encode a true base64_encode b b64encode b true base64_encode c b64encode c true base64_encode abc traceback most recent call last typeerror a bytes like object is required not str make sure the supplied data is a bytes like object the padding that will be added later append binary_stream with arbitrary binary digits 0 s by default to make its length a multiple of 6 encode every 6 binary digits to their corresponding base64 character decodes data according to rfc4648 this does the reverse operation of base64_encode we first transform the encoded data back to a binary stream take off the previously appended binary digits according to the padding at this point we would have a binary stream whose length is multiple of 8 the last step is to convert every 8 bits to a byte from base64 import b64decode a vghpcybwdwxsihjlcxvlc3qgaxmgcgfydcbvzibiywnrdg9izxjmzxn0mjah b ahr0chm6ly90b29scy5pzxrmlm9yzy9odg1sl3jmyzq2ndg c qq base64_decode a b64decode a true base64_decode b b64decode b true base64_decode c b64decode c true base64_decode abc traceback most recent call last assertionerror incorrect padding make sure encoded_data is either a string or a bytes like object in case encoded_data is a bytes like object make sure it contains only ascii characters so we convert it to a string object check if the encoded string contains non base64 characters check the padding remove padding if there is one
B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def base64_encode(data: bytes) -> bytes: if not isinstance(data, bytes): msg = f"a bytes-like object is required, not '{data.__class__.__name__}'" raise TypeError(msg) binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data) padding_needed = len(binary_stream) % 6 != 0 if padding_needed: padding = b"=" * ((6 - len(binary_stream) % 6) // 2) binary_stream += "0" * (6 - len(binary_stream) % 6) else: padding = b"" return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6], 2)] for index in range(0, len(binary_stream), 6) ).encode() + padding ) def base64_decode(encoded_data: str) -> bytes: if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str): msg = ( "argument should be a bytes-like object or ASCII string, " f"not '{encoded_data.__class__.__name__}'" ) raise TypeError(msg) if isinstance(encoded_data, bytes): try: encoded_data = encoded_data.decode("utf-8") except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters") padding = encoded_data.count("=") if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding" if padding: encoded_data = encoded_data[:-padding] binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data )[: -padding * 2] else: binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data ) data = [ int(binary_stream[index : index + 8], 2) for index in range(0, len(binary_stream), 8) ] return bytes(data) if __name__ == "__main__": import doctest doctest.testmod()
base85 ascii85 encoding and decoding https en wikipedia orgwikiascii85 ascii85encodeb b ascii85encodeb12345 b 0etoa2 ascii85encodebbase 85 b uxh 24 ascii85decodeb b ascii85decodeb0etoa2 b 12345 ascii85decodebuxh 24 b base 85 ascii85_encode b b ascii85_encode b 12345 b 0etoa2 ascii85_encode b base 85 b ux h 24 ascii85_decode b b ascii85_decode b 0etoa2 b 12345 ascii85_decode b ux h 24 b base 85
def _base10_to_85(d: int) -> str: return "".join(chr(d % 85 + 33)) + _base10_to_85(d // 85) if d > 0 else "" def _base85_to_10(digits: list) -> int: return sum(char * 85**i for i, char in enumerate(reversed(digits))) def ascii85_encode(data: bytes) -> bytes: binary_data = "".join(bin(ord(d))[2:].zfill(8) for d in data.decode("utf-8")) null_values = (32 * ((len(binary_data) // 32) + 1) - len(binary_data)) // 8 binary_data = binary_data.ljust(32 * ((len(binary_data) // 32) + 1), "0") b85_chunks = [int(_s, 2) for _s in map("".join, zip(*[iter(binary_data)] * 32))] result = "".join(_base10_to_85(chunk)[::-1] for chunk in b85_chunks) return bytes(result[:-null_values] if null_values % 4 != 0 else result, "utf-8") def ascii85_decode(data: bytes) -> bytes: null_values = 5 * ((len(data) // 5) + 1) - len(data) binary_data = data.decode("utf-8") + "u" * null_values b85_chunks = map("".join, zip(*[iter(binary_data)] * 5)) b85_segments = [[ord(_s) - 33 for _s in chunk] for chunk in b85_chunks] results = [bin(_base85_to_10(chunk))[2::].zfill(32) for chunk in b85_segments] char_chunks = [ [chr(int(_s, 2)) for _s in map("".join, zip(*[iter(r)] * 8))] for r in results ] result = "".join("".join(char) for char in char_chunks) offset = int(null_values % 5 == 0) return bytes(result[: offset - null_values], "utf-8") if __name__ == "__main__": import doctest doctest.testmod()
mohit radadiya this function generates the key in a cyclic manner until it s length isn t equal to the length of original text generatekeythe german attack secret secretsecretsecre this function returns the encrypted text generated with the help of the key ciphertextthe german attack secretsecretsecre bdc payuwl jpaiyi this function decrypts the encrypted text and returns the original text originaltextbdc payuwl jpaiyi secretsecretsecre the german attack this function generates the key in a cyclic manner until it s length isn t equal to the length of original text generate_key the german attack secret secretsecretsecre this function returns the encrypted text generated with the help of the key cipher_text the german attack secretsecretsecre bdc payuwl jpaiyi this function decrypts the encrypted text and returns the original text original_text bdc payuwl jpaiyi secretsecretsecre the german attack
from string import ascii_uppercase dict1 = {char: i for i, char in enumerate(ascii_uppercase)} dict2 = dict(enumerate(ascii_uppercase)) def generate_key(message: str, key: str) -> str: x = len(message) i = 0 while True: if x == i: i = 0 if len(key) == len(message): break key += key[i] i += 1 return key def cipher_text(message: str, key_new: str) -> str: cipher_text = "" i = 0 for letter in message: if letter == " ": cipher_text += " " else: x = (dict1[letter] - dict1[key_new[i]]) % 26 i += 1 cipher_text += dict2[x] return cipher_text def original_text(cipher_text: str, key_new: str) -> str: or_txt = "" i = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: x = (dict1[letter] + dict1[key_new[i]] + 26) % 26 i += 1 or_txt += dict2[x] return or_txt def main() -> None: message = "THE GERMAN ATTACK" key = "SECRET" key_new = generate_key(message, key) s = cipher_text(message, key_new) print(f"Encrypted Text = {s}") print(f"Original Text = {original_text(s, key_new)}") if __name__ == "__main__": import doctest doctest.testmod() main()
usrbinenv python3 the bifid cipher uses a polybius square to encipher a message in a way that makes it fairly difficult to decipher without knowing the secret https www braingle combrainteaserscodesbifid php return the pair of numbers that represents the given letter in the polybius square np arrayequalbifidcipher lettertonumbers a 1 1 true np arrayequalbifidcipher lettertonumbers u 4 5 true return the letter corresponding to the position index1 index2 in the polybius square bifidcipher numberstoletter4 5 u true bifidcipher numberstoletter1 1 a true return the encoded version of message according to the polybius cipher bifidcipher encode testmessage qtltbdxrxlk true bifidcipher encode test message qtltbdxrxlk true bifidcipher encode test j bifidcipher encode test i true return the decoded version of message according to the polybius cipher bifidcipher decode qtltbdxrxlk testmessage true usr bin env python3 the bifid cipher uses a polybius square to encipher a message in a way that makes it fairly difficult to decipher without knowing the secret https www braingle com brainteasers codes bifid php return the pair of numbers that represents the given letter in the polybius square np array_equal bifidcipher letter_to_numbers a 1 1 true np array_equal bifidcipher letter_to_numbers u 4 5 true return the letter corresponding to the position index1 index2 in the polybius square bifidcipher numbers_to_letter 4 5 u true bifidcipher numbers_to_letter 1 1 a true return the encoded version of message according to the polybius cipher bifidcipher encode testmessage qtltbdxrxlk true bifidcipher encode test message qtltbdxrxlk true bifidcipher encode test j bifidcipher encode test i true return the decoded version of message according to the polybius cipher bifidcipher decode qtltbdxrxlk testmessage true
import numpy as np SQUARE = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] class BifidCipher: def __init__(self) -> None: self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: index1, index2 = np.where(letter == self.SQUARE) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: letter = self.SQUARE[index1 - 1, index2 - 1] return letter def encode(self, message: str) -> str: message = message.lower() message = message.replace(" ", "") message = message.replace("j", "i") first_step = np.empty((2, len(message))) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[0, letter_index] = numbers[0] first_step[1, letter_index] = numbers[1] second_step = first_step.reshape(2 * len(message)) encoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[numbers_index * 2]) index2 = int(second_step[(numbers_index * 2) + 1]) letter = self.numbers_to_letter(index1, index2) encoded_message = encoded_message + letter return encoded_message def decode(self, message: str) -> str: message = message.lower() message.replace(" ", "") first_step = np.empty(2 * len(message)) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[letter_index * 2] = numbers[0] first_step[letter_index * 2 + 1] = numbers[1] second_step = first_step.reshape((2, len(message))) decoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[0, numbers_index]) index2 = int(second_step[1, numbers_index]) letter = self.numbers_to_letter(index1, index2) decoded_message = decoded_message + letter return decoded_message
encrypt encodes a given string with the caesar cipher and returns the encoded message parameters inputstring the plaintext that needs to be encoded key the number of letters to shift the message by optional alphabet none the alphabet used to encode the cipher if not specified the standard english alphabet with upper and lowercase letters is used returns a string containing the encoded ciphertext more on the caesar cipher the caesar cipher is named after julius caesar who used it when sending secret military messages to his troops this is a simple substitution cipher where every character in the plaintext is shifted by a certain number known as the key or shift example say we have the following message hello captain and our alphabet is made up of lower and uppercase letters abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz and our shift is 2 we can then encode the message one letter at a time h would become j since j is two letters away and so on if the shift is ever two large or our letter is at the end of the alphabet we just start at the beginning z would shift to a then b and so on our final message would be jgnnq ecrvckp further reading https en m wikipedia orgwikicaesarcipher doctests encrypt the quick brown fox jumps over the lazy dog 8 bpm ycqks jzwev nwf rcuxa wdmz bpm tihg lwo encrypt a very large key 8000 s nwjq dsjyw cwq encrypt a lowercase alphabet 5 abcdefghijklmnopqrstuvwxyz f qtbjwhfxj fqumfgjy set default alphabet to lower and upper case english chars the final result string append without encryption if character is not in the alphabet get the index of the new key and make sure it isn t too large append the encoded character to the alphabet decrypt decodes a given string of ciphertext and returns the decoded plaintext parameters inputstring the ciphertext that needs to be decoded key the number of letters to shift the message backwards by to decode optional alphabet none the alphabet used to decode the cipher if not specified the standard english alphabet with upper and lowercase letters is used returns a string containing the decoded plaintext more on the caesar cipher the caesar cipher is named after julius caesar who used it when sending secret military messages to his troops this is a simple substitution cipher where very character in the plaintext is shifted by a certain number known as the key or shift please keep in mind here we will be focused on decryption example say we have the following ciphertext jgnnq ecrvckp and our alphabet is made up of lower and uppercase letters abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz and our shift is 2 to decode the message we would do the same thing as encoding but in reverse the first letter j would become h remember we are decoding because h is two letters in reverse to the left of j we would continue doing this a letter like a would shift back to the end of the alphabet and would become z or y and so on our final message would be hello captain further reading https en m wikipedia orgwikicaesarcipher doctests decrypt bpm ycqks jzwev nwf rcuxa wdmz bpm tihg lwo 8 the quick brown fox jumps over the lazy dog decrypt s nwjq dsjyw cwq 8000 a very large key decrypt f qtbjwhfxj fqumfgjy 5 abcdefghijklmnopqrstuvwxyz a lowercase alphabet turn on decode mode by making the key negative bruteforce returns all the possible combinations of keys and the decoded strings in the form of a dictionary parameters inputstring the ciphertext that needs to be used during bruteforce optional alphabet none the alphabet used to decode the cipher if not specified the standard english alphabet with upper and lowercase letters is used more about brute force brute force is when a person intercepts a message or password not knowing the key and tries every single combination this is easy with the caesar cipher since there are only all the letters in the alphabet the more complex the cipher the larger amount of time it will take to do brute force ex say we have a 5 letter alphabet abcde for simplicity and we intercepted the following message dbc we could then just write out every combination ecd and so on until we reach a combination that makes sense cab further reading https en wikipedia orgwikibruteforce doctests bruteforcejfyumy xih n vlony zilwy gy 20 please don t brute force me bruteforce1 traceback most recent call last typeerror int object is not iterable set default alphabet to lower and upper case english chars to store data on all the combinations cycle through each combination decrypt the message and store the result in the data get user input run functions based on what the user chose encrypt encodes a given string with the caesar cipher and returns the encoded message parameters input_string the plain text that needs to be encoded key the number of letters to shift the message by optional alphabet none the alphabet used to encode the cipher if not specified the standard english alphabet with upper and lowercase letters is used returns a string containing the encoded cipher text more on the caesar cipher the caesar cipher is named after julius caesar who used it when sending secret military messages to his troops this is a simple substitution cipher where every character in the plain text is shifted by a certain number known as the key or shift example say we have the following message hello captain and our alphabet is made up of lower and uppercase letters abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz and our shift is 2 we can then encode the message one letter at a time h would become j since j is two letters away and so on if the shift is ever two large or our letter is at the end of the alphabet we just start at the beginning z would shift to a then b and so on our final message would be jgnnq ecrvckp further reading https en m wikipedia org wiki caesar_cipher doctests encrypt the quick brown fox jumps over the lazy dog 8 bpm ycqks jzwev nwf rcuxa wdmz bpm tihg lwo encrypt a very large key 8000 s nwjq dsjyw cwq encrypt a lowercase alphabet 5 abcdefghijklmnopqrstuvwxyz f qtbjwhfxj fqumfgjy set default alphabet to lower and upper case english chars the final result string append without encryption if character is not in the alphabet get the index of the new key and make sure it isn t too large append the encoded character to the alphabet decrypt decodes a given string of cipher text and returns the decoded plain text parameters input_string the cipher text that needs to be decoded key the number of letters to shift the message backwards by to decode optional alphabet none the alphabet used to decode the cipher if not specified the standard english alphabet with upper and lowercase letters is used returns a string containing the decoded plain text more on the caesar cipher the caesar cipher is named after julius caesar who used it when sending secret military messages to his troops this is a simple substitution cipher where very character in the plain text is shifted by a certain number known as the key or shift please keep in mind here we will be focused on decryption example say we have the following cipher text jgnnq ecrvckp and our alphabet is made up of lower and uppercase letters abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz and our shift is 2 to decode the message we would do the same thing as encoding but in reverse the first letter j would become h remember we are decoding because h is two letters in reverse to the left of j we would continue doing this a letter like a would shift back to the end of the alphabet and would become z or y and so on our final message would be hello captain further reading https en m wikipedia org wiki caesar_cipher doctests decrypt bpm ycqks jzwev nwf rcuxa wdmz bpm tihg lwo 8 the quick brown fox jumps over the lazy dog decrypt s nwjq dsjyw cwq 8000 a very large key decrypt f qtbjwhfxj fqumfgjy 5 abcdefghijklmnopqrstuvwxyz a lowercase alphabet turn on decode mode by making the key negative brute_force returns all the possible combinations of keys and the decoded strings in the form of a dictionary parameters input_string the cipher text that needs to be used during brute force optional alphabet none the alphabet used to decode the cipher if not specified the standard english alphabet with upper and lowercase letters is used more about brute force brute force is when a person intercepts a message or password not knowing the key and tries every single combination this is easy with the caesar cipher since there are only all the letters in the alphabet the more complex the cipher the larger amount of time it will take to do brute force ex say we have a 5 letter alphabet abcde for simplicity and we intercepted the following message dbc we could then just write out every combination ecd and so on until we reach a combination that makes sense cab further reading https en wikipedia org wiki brute_force doctests brute_force jfyumy xih n vlony zilwy gy 20 please don t brute force me brute_force 1 traceback most recent call last typeerror int object is not iterable set default alphabet to lower and upper case english chars to store data on all the combinations cycle through each combination decrypt the message and store the result in the data get user input run functions based on what the user chose
from __future__ import annotations from string import ascii_letters def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str: alpha = alphabet or ascii_letters result = "" for character in input_string: if character not in alpha: result += character else: new_key = (alpha.index(character) + key) % len(alpha) result += alpha[new_key] return result def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str: key *= -1 return encrypt(input_string, key, alphabet) def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]: alpha = alphabet or ascii_letters brute_force_data = {} for key in range(1, len(alpha) + 1): brute_force_data[key] = decrypt(input_string, key, alpha) return brute_force_data if __name__ == "__main__": while True: print(f'\n{"-" * 10}\n Menu\n{"-" * 10}') print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n") choice = input("\nWhat would you like to do?: ").strip() or "4" if choice not in ("1", "2", "3", "4"): print("Invalid choice, please enter a valid choice") elif choice == "1": input_string = input("Please enter the string to be encrypted: ") key = int(input("Please enter off-set: ").strip()) print(encrypt(input_string, key)) elif choice == "2": input_string = input("Please enter the string to be decrypted: ") key = int(input("Please enter off-set: ").strip()) print(decrypt(input_string, key)) elif choice == "3": input_string = input("Please enter the string to be decrypted: ") brute_force_data = brute_force(input_string) for key, value in brute_force_data.items(): print(f"Key: {key} | Message: {value}") elif choice == "4": print("Goodbye.") break
usrbinenv python3 basic usage arguments ciphertext str the text to decode encoded with the caesar cipher optional arguments cipheralphabet list the alphabet used for the cipher each letter is a string separated by commas frequenciesdict dict a dictionary of word frequencies where keys are the letters and values are a percentage representation of the frequency as a decimalfloat casesensitive bool a boolean value true if the case matters during decryption false if it doesn t returns a tuple in the form of mostlikelycipher mostlikelycipherchisquaredvalue decodedmostlikelycipher where mostlikelycipher is an integer representing the shift of the smallest chisquared statistic most likely key mostlikelycipherchisquaredvalue is a float representing the chisquared statistic of the most likely shift decodedmostlikelycipher is a string with the decoded cipher decoded by the mostlikelycipher key the chisquared test the caesar cipher the caesar cipher is a very insecure encryption algorithm however it has been used since julius caesar the cipher is a simple substitution cipher where each character in the plain text is replaced by a character in the alphabet a certain number of characters after the original character the number of characters away is called the shift or key for example plain text hello key 1 cipher text ifmmp each letter in hello has been shifted one to the right in the eng alphabet as you can imagine this doesn t provide lots of security in fact decrypting ciphertext by bruteforce is extremely easy even by hand however one way to do that is the chisquared test the chisquared test each letter in the english alphabet has a frequency or the amount of times it shows up compared to other letters usually expressed as a decimal representing the percentage likelihood the most common letter in the english language is e with a frequency of 0 11162 or 11 162 the test is completed in the following fashion 1 the ciphertext is decoded in a brute force way every combination of the 26 possible combinations 2 for every combination for each letter in the combination the average amount of times the letter should appear the message is calculated by multiplying the total number of characters by the frequency of the letter for example in a message of 100 characters e should appear around 11 162 times 3 then to calculate the margin of error the amount of times the letter should appear with the amount of times the letter does appear we use the chisquared test the following formula is used let n be the number of times the letter actually appears p be the predicted value of the number of times the letter should appear see 2 let v be the chisquared test result referred to here as chisquared valuestatistic n p2 v p 4 each chi squared value for each letter is then added up to the total the total is the chisquared statistic for that encryption key 5 the encryption key with the lowest chisquared value is the most likely to be the decoded answer further reading http practicalcryptography comcryptanalysistextcharacterisationchisquared statistic https en wikipedia orgwikiletterfrequency https en wikipedia orgwikichisquaredtest https en m wikipedia orgwikicaesarcipher doctests decryptcaesarwithchisquared dof pz aol jhlzhy jpwoly zv wvwbshy pa pz avv lhzf av jyhjr doctest normalizewhitespace 7 3129 228005747531 why is the caesar cipher so popular it is too easy to crack decryptcaesarwithchisquared crybd cdbsxq 10 233 35343938980898 short string decryptcaesarwithchisquared crybd cdbsxq casesensitivetrue 10 233 35343938980898 short string decryptcaesarwithchisquared12 traceback most recent call last attributeerror int object has no attribute lower if the argument is none or the user provided an empty dictionary frequencies of letters in the english language how much they show up custom frequencies dictionary chi squared statistic values cycle through all of the shifts decrypt the message with the shift try to index the letter in the alphabet append the character if it isn t in the alphabet loop through each letter in the decoded message with the shift get the amount of times the letter occurs in the message get the excepcted amount of times the letter should appear based on letter frequencies complete the chi squared statistic formula add the margin of error to the total chi squared statistic get the amount of times the letter occurs in the message get the excepcted amount of times the letter should appear based on letter frequencies complete the chi squared statistic formula add the margin of error to the total chi squared statistic add the data to the chisquaredstatisticvalues dictionary get the most likely cipher by finding the cipher with the smallest chi squared statistic get all the data from the most likely cipher key decoded message return the data on the most likely shift usr bin env python3 basic usage arguments ciphertext str the text to decode encoded with the caesar cipher optional arguments cipher_alphabet list the alphabet used for the cipher each letter is a string separated by commas frequencies_dict dict a dictionary of word frequencies where keys are the letters and values are a percentage representation of the frequency as a decimal float case_sensitive bool a boolean value true if the case matters during decryption false if it doesn t returns a tuple in the form of most_likely_cipher most_likely_cipher_chi_squared_value decoded_most_likely_cipher where most_likely_cipher is an integer representing the shift of the smallest chi squared statistic most likely key most_likely_cipher_chi_squared_value is a float representing the chi squared statistic of the most likely shift decoded_most_likely_cipher is a string with the decoded cipher decoded by the most_likely_cipher key the chi squared test the caesar cipher the caesar cipher is a very insecure encryption algorithm however it has been used since julius caesar the cipher is a simple substitution cipher where each character in the plain text is replaced by a character in the alphabet a certain number of characters after the original character the number of characters away is called the shift or key for example plain text hello key 1 cipher text ifmmp each letter in hello has been shifted one to the right in the eng alphabet as you can imagine this doesn t provide lots of security in fact decrypting ciphertext by brute force is extremely easy even by hand however one way to do that is the chi squared test the chi squared test each letter in the english alphabet has a frequency or the amount of times it shows up compared to other letters usually expressed as a decimal representing the percentage likelihood the most common letter in the english language is e with a frequency of 0 11162 or 11 162 the test is completed in the following fashion 1 the ciphertext is decoded in a brute force way every combination of the 26 possible combinations 2 for every combination for each letter in the combination the average amount of times the letter should appear the message is calculated by multiplying the total number of characters by the frequency of the letter for example in a message of 100 characters e should appear around 11 162 times 3 then to calculate the margin of error the amount of times the letter should appear with the amount of times the letter does appear we use the chi squared test the following formula is used let n be the number of times the letter actually appears p be the predicted value of the number of times the letter should appear see 2 let v be the chi squared test result referred to here as chi squared value statistic n p 2 v p 4 each chi squared value for each letter is then added up to the total the total is the chi squared statistic for that encryption key 5 the encryption key with the lowest chi squared value is the most likely to be the decoded answer further reading http practicalcryptography com cryptanalysis text characterisation chi squared statistic https en wikipedia org wiki letter_frequency https en wikipedia org wiki chi squared_test https en m wikipedia org wiki caesar_cipher doctests decrypt_caesar_with_chi_squared dof pz aol jhlzhy jpwoly zv wvwbshy pa pz avv lhzf av jyhjr doctest normalize_whitespace 7 3129 228005747531 why is the caesar cipher so popular it is too easy to crack decrypt_caesar_with_chi_squared crybd cdbsxq 10 233 35343938980898 short string decrypt_caesar_with_chi_squared crybd cdbsxq case_sensitive true 10 233 35343938980898 short string decrypt_caesar_with_chi_squared 12 traceback most recent call last attributeerror int object has no attribute lower if the argument is none or the user provided an empty dictionary frequencies of letters in the english language how much they show up custom frequencies dictionary chi squared statistic values cycle through all of the shifts decrypt the message with the shift try to index the letter in the alphabet append the character if it isn t in the alphabet loop through each letter in the decoded message with the shift get the amount of times the letter occurs in the message get the excepcted amount of times the letter should appear based on letter frequencies complete the chi squared statistic formula add the margin of error to the total chi squared statistic get the amount of times the letter occurs in the message get the excepcted amount of times the letter should appear based on letter frequencies complete the chi squared statistic formula add the margin of error to the total chi squared statistic add the data to the chi_squared_statistic_values dictionary get the most likely cipher by finding the cipher with the smallest chi squared statistic get all the data from the most likely cipher key decoded message return the data on the most likely shift
from __future__ import annotations def decrypt_caesar_with_chi_squared( ciphertext: str, cipher_alphabet: list[str] | None = None, frequencies_dict: dict[str, float] | None = None, case_sensitive: bool = False, ) -> tuple[int, float, str]: alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)] if not frequencies_dict: frequencies = { "a": 0.08497, "b": 0.01492, "c": 0.02202, "d": 0.04253, "e": 0.11162, "f": 0.02228, "g": 0.02015, "h": 0.06094, "i": 0.07546, "j": 0.00153, "k": 0.01292, "l": 0.04025, "m": 0.02406, "n": 0.06749, "o": 0.07507, "p": 0.01929, "q": 0.00095, "r": 0.07587, "s": 0.06327, "t": 0.09356, "u": 0.02758, "v": 0.00978, "w": 0.02560, "x": 0.00150, "y": 0.01994, "z": 0.00077, } else: frequencies = frequencies_dict if not case_sensitive: ciphertext = ciphertext.lower() chi_squared_statistic_values: dict[int, tuple[float, str]] = {} for shift in range(len(alphabet_letters)): decrypted_with_shift = "" for letter in ciphertext: try: new_key = (alphabet_letters.index(letter.lower()) - shift) % len( alphabet_letters ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: decrypted_with_shift += letter chi_squared_statistic = 0.0 for letter in decrypted_with_shift: if case_sensitive: letter = letter.lower() if letter in frequencies: occurrences = decrypted_with_shift.lower().count(letter) expected = frequencies[letter] * occurrences chi_letter_value = ((occurrences - expected) ** 2) / expected chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: occurrences = decrypted_with_shift.count(letter) expected = frequencies[letter] * occurrences chi_letter_value = ((occurrences - expected) ** 2) / expected chi_squared_statistic += chi_letter_value chi_squared_statistic_values[shift] = ( chi_squared_statistic, decrypted_with_shift, ) def chi_squared_statistic_values_sorting_key(key: int) -> tuple[float, str]: return chi_squared_statistic_values[key] most_likely_cipher: int = min( chi_squared_statistic_values, key=chi_squared_statistic_values_sorting_key, ) ( most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, ) = chi_squared_statistic_values[most_likely_cipher] return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
nathan damon bizzfitch on github testmillerrabin deterministic millerrabin algorithm for primes 3 32e24 uses numerical analysis results to return whether or not the passed number is prime if the passed number is above the upper limit and allowprobable is true then a return value of true indicates that n is probably prime this test does not allow false negatives a return value of false is always composite parameters n int the integer to be tested since we usually care if a number is prime n 2 returns false instead of raising a valueerror allowprobable bool default false whether or not to test n above the upper bound of the deterministic test raises valueerror reference https en wikipedia orgwikimillere28093rabinprimalitytest array bounds provided by analysis then we have our last prime to check break up n 1 into a power of 2 s and remaining odd component essentially solve for d 2 s n 1 see article for analysis explanation for m this loop will not determine compositeness if pr is false then the above loop never evaluated to true and the n must be composite testing a nontrivial ends in 1 3 7 9 composite and a prime in each range 2047 1373653 25326001 3215031751 2152302898747 3474749660383 341550071728321 3825123056546413051 318665857834031151167461 3317044064679887385961981 upper limit for probabilistic test deterministic miller rabin algorithm for primes 3 32e24 uses numerical analysis results to return whether or not the passed number is prime if the passed number is above the upper limit and allow_probable is true then a return value of true indicates that n is probably prime this test does not allow false negatives a return value of false is always composite parameters n int the integer to be tested since we usually care if a number is prime n 2 returns false instead of raising a valueerror allow_probable bool default false whether or not to test n above the upper bound of the deterministic test raises valueerror reference https en wikipedia org wiki miller e2 80 93rabin_primality_test can quickly check last digit array bounds provided by analysis then we have our last prime to check break up n 1 into a power of 2 s and remaining odd component essentially solve for d 2 s n 1 see article for analysis explanation for m this loop will not determine compositeness if pr is false then the above loop never evaluated to true and the n must be composite testing a nontrivial ends in 1 3 7 9 composite and a prime in each range 2047 1_373_653 25_326_001 3_215_031_751 2_152_302_898_747 3_474_749_660_383 341_550_071_728_321 3_825_123_056_546_413_051 318_665_857_834_031_151_167_461 3_317_044_064_679_887_385_961_981 upper limit for probabilistic test
def miller_rabin(n: int, allow_probable: bool = False) -> bool: if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): return False if n > 3_317_044_064_679_887_385_961_981 and not allow_probable: raise ValueError( "Warning: upper bound of deterministic test is exceeded. " "Pass allow_probable=True to allow probabilistic test. " "A return value of True indicates a probable prime." ) bounds = [ 2_047, 1_373_653, 25_326_001, 3_215_031_751, 2_152_302_898_747, 3_474_749_660_383, 341_550_071_728_321, 1, 3_825_123_056_546_413_051, 1, 1, 318_665_857_834_031_151_167_461, 3_317_044_064_679_887_385_961_981, ] primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(bounds, 1): if n < _p: plist = primes[:idx] break d, s = n - 1, 0 while d % 2 == 0: d //= 2 s += 1 for prime in plist: pr = False for r in range(s): m = pow(prime, d * 2**r, n) if (r == 0 and m == 1) or ((m + 1) % n == 0): pr = True break if pr: continue return False return True def test_miller_rabin() -> None: assert not miller_rabin(561) assert miller_rabin(563) assert not miller_rabin(838_201) assert miller_rabin(838_207) assert not miller_rabin(17_316_001) assert miller_rabin(17_316_017) assert not miller_rabin(3_078_386_641) assert miller_rabin(3_078_386_653) assert not miller_rabin(1_713_045_574_801) assert miller_rabin(1_713_045_574_819) assert not miller_rabin(2_779_799_728_307) assert miller_rabin(2_779_799_728_327) assert not miller_rabin(113_850_023_909_441) assert miller_rabin(113_850_023_909_527) assert not miller_rabin(1_275_041_018_848_804_351) assert miller_rabin(1_275_041_018_848_804_391) assert not miller_rabin(79_666_464_458_507_787_791_867) assert miller_rabin(79_666_464_458_507_787_791_951) assert not miller_rabin(552_840_677_446_647_897_660_333) assert miller_rabin(552_840_677_446_647_897_660_359) if __name__ == "__main__": test_miller_rabin()
find a primitive root modulo modulus if one exists args modulus the modulus for which to find a primitive root returns the primitive root if one exists or none if there is none examples findprimitive7 modulo 7 has primitive root 3 3 findprimitive11 modulo 11 has primitive root 2 2 findprimitive8 none modulo 8 has no primitive root true find a primitive root modulo modulus if one exists args modulus the modulus for which to find a primitive root returns the primitive root if one exists or none if there is none examples find_primitive 7 modulo 7 has primitive root 3 3 find_primitive 11 modulo 11 has primitive root 2 2 find_primitive 8 none modulo 8 has no primitive root true
from __future__ import annotations def find_primitive(modulus: int) -> int | None: for r in range(1, modulus): li = [] for x in range(modulus - 1): val = pow(r, x, modulus) if val in li: break li.append(val) else: return r return None if __name__ == "__main__": import doctest doctest.testmod() prime = int(input("Enter a prime number q: ")) primitive_root = find_primitive(prime) if primitive_root is None: print(f"Cannot find the primitive for the value: {primitive_root!r}") else: a_private = int(input("Enter private key of A: ")) a_public = pow(primitive_root, a_private, prime) b_private = int(input("Enter private key of B: ")) b_public = pow(primitive_root, b_private, prime) a_secret = pow(b_public, a_private, prime) b_secret = pow(a_public, b_private, prime) print("The key value generated by A is: ", a_secret) print("The key value generated by B is: ", b_secret)
rfc 3526 more modular exponential modp diffiehellman groups for internet key exchange ike https tools ietf orghtmlrfc3526 1536bit 2048bit 3072bit 4096bit 6144bit 8192bit class to represent the diffiehellman key exchange protocol alice diffiehellman bob diffiehellman aliceprivate alice getprivatekey alicepublic alice generatepublickey bobprivate bob getprivatekey bobpublic bob generatepublickey generating shared key using the dh object aliceshared alice generatesharedkeybobpublic bobshared bob generatesharedkeyalicepublic assert aliceshared bobshared generating shared key using static methods aliceshared diffiehellman generatesharedkeystatic aliceprivate bobpublic bobshared diffiehellman generatesharedkeystatic bobprivate alicepublic assert aliceshared bobshared current minimum recommendation is 2048 bit group 14 check if the other public key is valid based on nist sp80056 check if the other public key is valid based on nist sp80056 rfc 3526 more modular exponential modp diffie hellman groups for internet key exchange ike https tools ietf org html rfc3526 1536 bit 2048 bit 3072 bit 4096 bit 6144 bit 8192 bit class to represent the diffie hellman key exchange protocol alice diffiehellman bob diffiehellman alice_private alice get_private_key alice_public alice generate_public_key bob_private bob get_private_key bob_public bob generate_public_key generating shared key using the dh object alice_shared alice generate_shared_key bob_public bob_shared bob generate_shared_key alice_public assert alice_shared bob_shared generating shared key using static methods alice_shared diffiehellman generate_shared_key_static alice_private bob_public bob_shared diffiehellman generate_shared_key_static bob_private alice_public assert alice_shared bob_shared current minimum recommendation is 2048 bit group 14 check if the other public key is valid based on nist sp800 56 check if the other public key is valid based on nist sp800 56
from binascii import hexlify from hashlib import sha256 from os import urandom primes = { 5: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, 14: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" "15728E5A8AACAA68FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, 15: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, 16: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" "FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, 17: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" "6DCC4024FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, 18: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4" "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300" "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568" "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B" "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A" "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36" "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1" "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92" "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47" "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, } class DiffieHellman: def __init__(self, group: int = 14) -> None: if group not in primes: raise ValueError("Unsupported Group") self.prime = primes[group]["prime"] self.generator = primes[group]["generator"] self.__private_key = int(hexlify(urandom(32)), base=16) def get_private_key(self) -> str: return hex(self.__private_key)[2:] def generate_public_key(self) -> str: public_key = pow(self.generator, self.__private_key, self.prime) return hex(public_key)[2:] def is_valid_public_key(self, key: int) -> bool: return ( 2 <= key <= self.prime - 2 and pow(key, (self.prime - 1) // 2, self.prime) == 1 ) def generate_shared_key(self, other_key_str: str) -> str: other_key = int(other_key_str, base=16) if not self.is_valid_public_key(other_key): raise ValueError("Invalid public key") shared_key = pow(other_key, self.__private_key, self.prime) return sha256(str(shared_key).encode()).hexdigest() @staticmethod def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool: return ( 2 <= remote_public_key_str <= prime - 2 and pow(remote_public_key_str, (prime - 1) // 2, prime) == 1 ) @staticmethod def generate_shared_key_static( local_private_key_str: str, remote_public_key_str: str, group: int = 14 ) -> str: local_private_key = int(local_private_key_str, base=16) remote_public_key = int(remote_public_key_str, base=16) prime = primes[group]["prime"] if not DiffieHellman.is_valid_public_key_static(remote_public_key, prime): raise ValueError("Invalid public key") shared_key = pow(remote_public_key, local_private_key, prime) return sha256(str(shared_key).encode()).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
i have written my code naively same as definition of primitive root however every time i run this program memory exceeded so i used 4 80 algorithm in handbook of applied cryptographycrc press isbn 0849385237 october 1996 and it seems to run nicely i have written my code naively same as definition of primitive root however every time i run this program memory exceeded so i used 4 80 algorithm in handbook of applied cryptography crc press isbn 0 8493 8523 7 october 1996 and it seems to run nicely select large prime number one primitive root on modulo p private_key have to be greater than 2 for safety
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller min_primitive_root = 3 def primitive_root(p_val: int) -> int: print("Generating primitive root of p") while True: g = random.randrange(3, p_val) if pow(g, 2, p_val) == 1: continue if pow(g, p_val, p_val) == 1: continue return g def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print("Generating prime p...") p = rabin_miller.generate_large_prime(key_size) e_1 = primitive_root(p) d = random.randrange(3, p) e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p) public_key = (key_size, e_1, e_2, p) private_key = (key_size, d) return public_key, private_key def make_key_files(name: str, key_size: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." ) sys.exit() public_key, private_key = generate_key(key_size) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as fo: fo.write(f"{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}") print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as fo: fo.write(f"{private_key[0]},{private_key[1]}") def main() -> None: print("Making key files...") make_key_files("elgamal", 2048) print("Key files generation successful") if __name__ == "__main__": main()
wikipedia https en wikipedia orgwikienigmamachine video explanation https youtu beqwqvmqfob2e also check out numberphile s and computerphile s videos on this topic this module contains function enigma which emulates the famous enigma machine from wwii module includes enigma function showcase of function usage 9 randomly generated rotors reflector aka static rotor original alphabet trapincho used alphabet from string asciiuppercase default selection rotors reflector extra rotors checks if the values can be used for the enigma function validator1 1 1 rotor1 rotor2 rotor3 poland 1 1 1 egzwvonahdclfqmsipjbyukxtr fobhmdkexqnraulpgsjvtyiczw zjxesiuqlhavrmdoygtnfwpbkc p o o p l a a l n d d n param rotpos rotorpositon param rotsel rotorselection param pb plugb validated and transformed return rotpos rotsel pb checks if there are 3 unique rotors checks if rotor positions are valid validates string and returns dict https en wikipedia orgwikienigmamachineplugboard plugboard pictures p i i p c t t c u r r u e s s e plugboard poland p o o p l a a l n d d n in the code pb stands for plugboard pairs can be separated by spaces param pbstring string containing plugboard setting for the enigma machine return dictionary containing converted pairs tests the input string if it a is type string b has even length so pairs can be made checks if all characters are unique created the dictionary the only difference with realworld enigma is that i allowed string input all characters are converted to uppercase nonletter symbol are ignored how it works for every letter in the message input letter goes into the plugboard if it is connected to another one switch it letter goes through 3 rotors each rotor can be represented as 2 sets of symbol where one is shuffled each symbol from the first set has corresponding symbol in the second set and vice versa example abcdefghijklmnopqrstuvwxyz e g fd and df vklepdbgrnwtfcjohqamuzyixs symbol then goes through reflector static rotor there it is switched with paired symbol the reflector can be represented as2 sets each with half of the alphanet there are usually 10 pairs of letters example abcdefghijklm e g e is paired to x zyxwvutsrqpon so when e goes in x goes out and vice versa letter then goes through the rotors again if the letter is connected to plugboard it is switched return the letter enigma hello world 1 2 1 plugb pictures koryh juhhi enigma koryh juhhi 1 2 1 plugb pictures hello world enigma hello world 1 1 1 plugb pictures fpncz qwobu enigma fpncz qwobu 1 1 1 plugb pictures hello world param text input message param rotorposition tuple with 3 values in range 1 26 param rotorselection tuple with 3 rotors param plugb string containing plugboard configuration default return endecrypted string encryptiondecryption process 1st plugboard rotor ra rotor rb rotor rc reflector this is the reason you don t need another machine to decipher 2nd rotors 2nd plugboard movesresets rotor positions else pass error could be also raised raise valueerror invalid symbol reprsymbol used alphabet from string ascii_uppercase default selection rotors reflector extra rotors checks if the values can be used for the enigma function _validator 1 1 1 rotor1 rotor2 rotor3 poland 1 1 1 egzwvonahdclfqmsipjbyukxtr fobhmdkexqnraulpgsjvtyiczw zjxesiuqlhavrmdoygtnfwpbkc p o o p l a a l n d d n param rotpos rotor_positon param rotsel rotor_selection param pb plugb validated and transformed return rotpos rotsel pb checks if there are 3 unique rotors checks if rotor positions are valid validates string and returns dict https en wikipedia org wiki enigma_machine plugboard _plugboard pictures p i i p c t t c u r r u e s s e _plugboard poland p o o p l a a l n d d n in the code pb stands for plugboard pairs can be separated by spaces param pbstring string containing plugboard setting for the enigma machine return dictionary containing converted pairs tests the input string if it a is type string b has even length so pairs can be made checks if all characters are unique created the dictionary the only difference with real world enigma is that i allowed string input all characters are converted to uppercase non letter symbol are ignored how it works for every letter in the message input letter goes into the plugboard if it is connected to another one switch it letter goes through 3 rotors each rotor can be represented as 2 sets of symbol where one is shuffled each symbol from the first set has corresponding symbol in the second set and vice versa example abcdefghijklmnopqrstuvwxyz e g f d and d f vklepdbgrnwtfcjohqamuzyixs symbol then goes through reflector static rotor there it is switched with paired symbol the reflector can be represented as2 sets each with half of the alphanet there are usually 10 pairs of letters example abcdefghijklm e g e is paired to x zyxwvutsrqpon so when e goes in x goes out and vice versa letter then goes through the rotors again if the letter is connected to plugboard it is switched return the letter enigma hello world 1 2 1 plugb pictures koryh juhhi enigma koryh juhhi 1 2 1 plugb pictures hello world enigma hello world 1 1 1 plugb pictures fpncz qwobu enigma fpncz qwobu 1 1 1 plugb pictures hello world param text input message param rotor_position tuple with 3 values in range 1 26 param rotor_selection tuple with 3 rotors param plugb string containing plugboard configuration default return en decrypted string encryption decryption process 1st plugboard rotor ra rotor rb rotor rc reflector this is the reason you don t need another machine to decipher 2nd rotors 2nd plugboard moves resets rotor positions else pass error could be also raised raise valueerror invalid symbol repr symbol
from __future__ import annotations RotorPositionT = tuple[int, int, int] RotorSelectionT = tuple[str, str, str] abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR" rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW" rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC" reflector = { "A": "N", "N": "A", "B": "O", "O": "B", "C": "P", "P": "C", "D": "Q", "Q": "D", "E": "R", "R": "E", "F": "S", "S": "F", "G": "T", "T": "G", "H": "U", "U": "H", "I": "V", "V": "I", "J": "W", "W": "J", "K": "X", "X": "K", "L": "Y", "Y": "L", "M": "Z", "Z": "M", } rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA" rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM" rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN" rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE" rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN" rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS" def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: if (unique_rotsel := len(set(rotsel))) < 3: msg = f"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(msg) rotorpos1, rotorpos2, rotorpos3 = rotpos if not 0 < rotorpos1 <= len(abc): msg = f"First rotor position is not within range of 1..26 ({rotorpos1}" raise ValueError(msg) if not 0 < rotorpos2 <= len(abc): msg = f"Second rotor position is not within range of 1..26 ({rotorpos2})" raise ValueError(msg) if not 0 < rotorpos3 <= len(abc): msg = f"Third rotor position is not within range of 1..26 ({rotorpos3})" raise ValueError(msg) pbdict = _plugboard(pb) return rotpos, rotsel, pbdict def _plugboard(pbstring: str) -> dict[str, str]: if not isinstance(pbstring, str): msg = f"Plugboard setting isn't type string ({type(pbstring)})" raise TypeError(msg) elif len(pbstring) % 2 != 0: msg = f"Odd number of symbols ({len(pbstring)})" raise Exception(msg) elif pbstring == "": return {} pbstring.replace(" ", "") tmppbl = set() for i in pbstring: if i not in abc: msg = f"'{i}' not in list of symbols" raise Exception(msg) elif i in tmppbl: msg = f"Duplicate symbol ({i})" raise Exception(msg) else: tmppbl.add(i) del tmppbl pb = {} for j in range(0, len(pbstring) - 1, 2): pb[pbstring[j]] = pbstring[j + 1] pb[pbstring[j + 1]] = pbstring[j] return pb def enigma( text: str, rotor_position: RotorPositionT, rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3), plugb: str = "", ) -> str: text = text.upper() rotor_position, rotor_selection, plugboard = _validator( rotor_position, rotor_selection, plugb.upper() ) rotorpos1, rotorpos2, rotorpos3 = rotor_position rotor1, rotor2, rotor3 = rotor_selection rotorpos1 -= 1 rotorpos2 -= 1 rotorpos3 -= 1 result = [] for symbol in text: if symbol in abc: if symbol in plugboard: symbol = plugboard[symbol] index = abc.index(symbol) + rotorpos1 symbol = rotor1[index % len(abc)] index = abc.index(symbol) + rotorpos2 symbol = rotor2[index % len(abc)] index = abc.index(symbol) + rotorpos3 symbol = rotor3[index % len(abc)] symbol = reflector[symbol] symbol = abc[rotor3.index(symbol) - rotorpos3] symbol = abc[rotor2.index(symbol) - rotorpos2] symbol = abc[rotor1.index(symbol) - rotorpos1] if symbol in plugboard: symbol = plugboard[symbol] rotorpos1 += 1 if rotorpos1 >= len(abc): rotorpos1 = 0 rotorpos2 += 1 if rotorpos2 >= len(abc): rotorpos2 = 0 rotorpos3 += 1 if rotorpos3 >= len(abc): rotorpos3 = 0 result.append(symbol) return "".join(result) if __name__ == "__main__": message = "This is my Python script that emulates the Enigma machine from WWII." rotor_pos = (1, 1, 1) pb = "pictures" rotor_sel = (rotor2, rotor4, rotor8) en = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
python program for the fractionated morse cipher the fractionated morse cipher first converts the plaintext to morse code then enciphers fixedsize blocks of morse code back to letters this procedure means plaintext letters are mixed into the ciphertext letters making it more secure than substitution ciphers http practicalcryptography comciphersfractionatedmorsecipher define possible trigrams of morse code create a reverse dictionary for morse code encode a plaintext message into morse code args plaintext the plaintext message to encode returns the morse code representation of the plaintext message example encodetomorsedefend the east x x x x x xxx x xx x x x encrypt a plaintext message using fractionated morse cipher args plaintext the plaintext message to encrypt key the encryption key returns the encrypted ciphertext example encryptfractionatedmorsedefend the east roundtable esoavvljrsstrx ensure morsecode length is a multiple of 3 decrypt a ciphertext message encrypted with fractionated morse cipher args ciphertext the ciphertext message to decrypt key the decryption key returns the decrypted plaintext message example decryptfractionatedmorseesoavvljrsstrx roundtable defend the east example usage of fractionated morse cipher define possible trigrams of morse code create a reverse dictionary for morse code encode a plaintext message into morse code args plaintext the plaintext message to encode returns the morse code representation of the plaintext message example encode_to_morse defend the east x x x x x xx x x xx x x x encrypt a plaintext message using fractionated morse cipher args plaintext the plaintext message to encrypt key the encryption key returns the encrypted ciphertext example encrypt_fractionated_morse defend the east roundtable esoavvljrsstrx ensure morse_code length is a multiple of 3 decrypt a ciphertext message encrypted with fractionated morse cipher args ciphertext the ciphertext message to decrypt key the decryption key returns the decrypted plaintext message example decrypt_fractionated_morse esoavvljrsstrx roundtable defend the east example usage of fractionated morse cipher
import string MORSE_CODE_DICT = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", " ": "", } MORSE_COMBINATIONS = [ "...", "..-", "..x", ".-.", ".--", ".-x", ".x.", ".x-", ".xx", "-..", "-.-", "-.x", "--.", "---", "--x", "-x.", "-x-", "-xx", "x..", "x.-", "x.x", "x-.", "x--", "x-x", "xx.", "xx-", "xxx", ] REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()} def encode_to_morse(plaintext: str) -> str: return "x".join([MORSE_CODE_DICT.get(letter.upper(), "") for letter in plaintext]) def encrypt_fractionated_morse(plaintext: str, key: str) -> str: morse_code = encode_to_morse(plaintext) key = key.upper() + string.ascii_uppercase key = "".join(sorted(set(key), key=key.find)) padding_length = 3 - (len(morse_code) % 3) morse_code += "x" * padding_length fractionated_morse_dict = {v: k for k, v in zip(key, MORSE_COMBINATIONS)} fractionated_morse_dict["xxx"] = "" encrypted_text = "".join( [ fractionated_morse_dict[morse_code[i : i + 3]] for i in range(0, len(morse_code), 3) ] ) return encrypted_text def decrypt_fractionated_morse(ciphertext: str, key: str) -> str: key = key.upper() + string.ascii_uppercase key = "".join(sorted(set(key), key=key.find)) inverse_fractionated_morse_dict = dict(zip(key, MORSE_COMBINATIONS)) morse_code = "".join( [inverse_fractionated_morse_dict.get(letter, "") for letter in ciphertext] ) decrypted_text = "".join( [REVERSE_DICT[code] for code in morse_code.split("x")] ).strip() return decrypted_text if __name__ == "__main__": plaintext = "defend the east" print("Plain Text:", plaintext) key = "ROUNDTABLE" ciphertext = encrypt_fractionated_morse(plaintext, key) print("Encrypted:", ciphertext) decrypted_text = decrypt_fractionated_morse(ciphertext, key) print("Decrypted:", decrypted_text)
hill cipher the hillcipher class below implements the hill cipher algorithm which uses modern linear algebra techniques to encode and decode text using an encryption key matrix algorithm let the order of the encryption key be n as it is a square matrix your text is divided into batches of length n and converted to numerical vectors by a simple mapping starting with a0 and so on the key is then multiplied with the newly created batch vector to obtain the encoded vector after each multiplication modular 36 calculations are performed on the vectors so as to bring the numbers between 0 and 36 and then mapped with their corresponding alphanumerics while decrypting the decrypting key is found which is the inverse of the encrypting key modular 36 the same process is repeated for decrypting to get the original message back constraints the determinant of the encryption key matrix must be relatively prime w r t 36 note this implementation only considers alphanumerics in the text if the length of the text to be encrypted is not a multiple of the break keythe length of one batch of letters the last character of the text is added to the text until the length of the text reaches a multiple of the breakkey so the text after decrypting might be a little different than the original text references https apprendreenligne netcryptohillhillciph pdf https www youtube comwatch vkfmneskzs2o https www youtube comwatch v4rhlndqcjpa this cipher takes alphanumerics into account i e a total of 36 characters take x and return x lenkeystring encryptkey is an nxn numpy array hillcipher hillciphernumpy array2 5 1 6 hillcipher replaceletters t 19 hillcipher replaceletters 0 26 hillcipher hillciphernumpy array2 5 1 6 hillcipher replacedigits19 t hillcipher replacedigits26 0 hillcipher hillciphernumpy array2 5 1 6 hillcipher checkdeterminant hillcipher hillciphernumpy array2 5 1 6 hillcipher processtext testing hill cipher testinghillcipherr hillcipher processtext hello helloo hillcipher hillciphernumpy array2 5 1 6 hillcipher encrypt testing hill cipher whxyjolm9c6xt085ll hillcipher encrypt hello 85ff00 hillcipher hillciphernumpy array2 5 1 6 hillcipher makedecryptkey array 6 25 5 26 hillcipher hillciphernumpy array2 5 1 6 hillcipher decrypt whxyjolm9c6xt085ll testinghillcipherr hillcipher decrypt 85ff00 helloo this cipher takes alphanumerics into account i e a total of 36 characters take x and return x len key_string encrypt_key is an nxn numpy array mod36 calc s on the encrypt key validate the determinant of the encryption key hill_cipher hillcipher numpy array 2 5 1 6 hill_cipher replace_letters t 19 hill_cipher replace_letters 0 26 hill_cipher hillcipher numpy array 2 5 1 6 hill_cipher replace_digits 19 t hill_cipher replace_digits 26 0 hill_cipher hillcipher numpy array 2 5 1 6 hill_cipher check_determinant hill_cipher hillcipher numpy array 2 5 1 6 hill_cipher process_text testing hill cipher testinghillcipherr hill_cipher process_text hello helloo hill_cipher hillcipher numpy array 2 5 1 6 hill_cipher encrypt testing hill cipher whxyjolm9c6xt085ll hill_cipher encrypt hello 85ff00 hill_cipher hillcipher numpy array 2 5 1 6 hill_cipher make_decrypt_key array 6 25 5 26 hill_cipher hillcipher numpy array 2 5 1 6 hill_cipher decrypt whxyjolm9c6xt085ll testinghillcipherr hill_cipher decrypt 85ff00 helloo
import string import numpy from maths.greatest_common_divisor import greatest_common_divisor class HillCipher: key_string = string.ascii_uppercase + string.digits modulus = numpy.vectorize(lambda x: x % 36) to_int = numpy.vectorize(round) def __init__(self, encrypt_key: numpy.ndarray) -> None: self.encrypt_key = self.modulus(encrypt_key) self.check_determinant() self.break_key = encrypt_key.shape[0] def replace_letters(self, letter: str) -> int: return self.key_string.index(letter) def replace_digits(self, num: int) -> str: return self.key_string[round(num)] def check_determinant(self) -> None: det = round(numpy.linalg.det(self.encrypt_key)) if det < 0: det = det % len(self.key_string) req_l = len(self.key_string) if greatest_common_divisor(det, len(self.key_string)) != 1: msg = ( f"determinant modular {req_l} of encryption key({det}) " f"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(msg) def process_text(self, text: str) -> str: chars = [char for char in text.upper() if char in self.key_string] last = chars[-1] while len(chars) % self.break_key != 0: chars.append(last) return "".join(chars) def encrypt(self, text: str) -> str: text = self.process_text(text.upper()) encrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): batch = text[i : i + self.break_key] vec = [self.replace_letters(char) for char in batch] batch_vec = numpy.array([vec]).T batch_encrypted = self.modulus(self.encrypt_key.dot(batch_vec)).T.tolist()[ 0 ] encrypted_batch = "".join( self.replace_digits(num) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def make_decrypt_key(self) -> numpy.ndarray: det = round(numpy.linalg.det(self.encrypt_key)) if det < 0: det = det % len(self.key_string) det_inv = None for i in range(len(self.key_string)): if (det * i) % len(self.key_string) == 1: det_inv = i break inv_key = ( det_inv * numpy.linalg.det(self.encrypt_key) * numpy.linalg.inv(self.encrypt_key) ) return self.to_int(self.modulus(inv_key)) def decrypt(self, text: str) -> str: decrypt_key = self.make_decrypt_key() text = self.process_text(text.upper()) decrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): batch = text[i : i + self.break_key] vec = [self.replace_letters(char) for char in batch] batch_vec = numpy.array([vec]).T batch_decrypted = self.modulus(decrypt_key.dot(batch_vec)).T.tolist()[0] decrypted_batch = "".join( self.replace_digits(num) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def main() -> None: n = int(input("Enter the order of the encryption key: ")) hill_matrix = [] print("Enter each row of the encryption key with space separated integers") for _ in range(n): row = [int(x) for x in input().split()] hill_matrix.append(row) hc = HillCipher(numpy.array(hill_matrix)) print("Would you like to encrypt or decrypt some text? (1 or 2)") option = input("\n1. Encrypt\n2. Decrypt\n") if option == "1": text_e = input("What text would you like to encrypt?: ") print("Your encrypted text is:") print(hc.encrypt(text_e)) elif option == "2": text_d = input("What text would you like to decrypt?: ") print("Your decrypted text is:") print(hc.decrypt(text_d)) if __name__ == "__main__": import doctest doctest.testmod() main()
for keyword hello h e l o a b c d f g i j k m n p q r s t u v w x y z and map vertically mixedkeywordcollege university true doctest normalizewhitespace a c b a c i d p e u f z g o h b i j j q k v l l m d n k o r p w q e r f s m t s u x v g w h x n y t z y xkjgufmjst mixedkeywordcollege university false doctest normalizewhitespace xkjgufmjst create a list of unique characters in the keyword their order matters it determines how we will map plaintext characters to the ciphertext the number of those unique characters will determine the number of rows create a shifted version of the alphabet create a modified alphabet by splitting the shifted alphabet into rows map the alphabet characters to the modified alphabet characters going vertically through the modified alphabet consider columns first if current row the last one is too short break out of loop map current letter to letter in modified alphabet create the encrypted text by mapping the plaintext to the modified alphabet example use for keyword hello h e l o a b c d f g i j k m n p q r s t u v w x y z and map vertically mixed_keyword college university true doctest normalize_whitespace a c b a c i d p e u f z g o h b i j j q k v l l m d n k o r p w q e r f s m t s u x v g w h x n y t z y xkjgufmjst mixed_keyword college university false doctest normalize_whitespace xkjgufmjst create a list of unique characters in the keyword their order matters it determines how we will map plaintext characters to the ciphertext the number of those unique characters will determine the number of rows create a shifted version of the alphabet create a modified alphabet by splitting the shifted alphabet into rows map the alphabet characters to the modified alphabet characters going vertically through the modified alphabet consider columns first if current row the last one is too short break out of loop map current letter to letter in modified alphabet create the encrypted text by mapping the plaintext to the modified alphabet example use
from string import ascii_uppercase def mixed_keyword( keyword: str, plaintext: str, verbose: bool = False, alphabet: str = ascii_uppercase ) -> str: keyword = keyword.upper() plaintext = plaintext.upper() alphabet_set = set(alphabet) unique_chars = [] for char in keyword: if char in alphabet_set and char not in unique_chars: unique_chars.append(char) num_unique_chars_in_keyword = len(unique_chars) shifted_alphabet = unique_chars + [ char for char in alphabet if char not in unique_chars ] modified_alphabet = [ shifted_alphabet[k : k + num_unique_chars_in_keyword] for k in range(0, 26, num_unique_chars_in_keyword) ] mapping = {} letter_index = 0 for column in range(num_unique_chars_in_keyword): for row in modified_alphabet: if len(row) <= column: break mapping[alphabet[letter_index]] = row[column] letter_index += 1 if verbose: print(mapping) return "".join(mapping[char] if char in mapping else char for char in plaintext) if __name__ == "__main__": print(mixed_keyword("college", "UNIVERSITY"))
translatemessageqwertyuiopasdfghjklzxcvbnm hello world encrypt pcssi bidsm loop through each symbol in the message encryptdecrypt the symbol symbol is not in letters just add it encryptmessageqwertyuiopasdfghjklzxcvbnm hello world pcssi bidsm decryptmessageqwertyuiopasdfghjklzxcvbnm hello world itssg vgksr translate_message qwertyuiopasdfghjklzxcvbnm hello world encrypt pcssi bidsm loop through each symbol in the message encrypt decrypt the symbol symbol is not in letters just add it encrypt_message qwertyuiopasdfghjklzxcvbnm hello world pcssi bidsm decrypt_message qwertyuiopasdfghjklzxcvbnm hello world itssg vgksr set to encrypt or decrypt
from typing import Literal LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def translate_message( key: str, message: str, mode: Literal["encrypt", "decrypt"] ) -> str: chars_a = LETTERS if mode == "decrypt" else key chars_b = key if mode == "decrypt" else LETTERS translated = "" for symbol in message: if symbol.upper() in chars_a: sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: translated += symbol return translated def encrypt_message(key: str, message: str) -> str: return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: return translate_message(key, message, "decrypt") def main() -> None: message = "Hello World" key = "QWERTYUIOPASDFGHJKLZXCVBNM" mode = "decrypt" if mode == "encrypt": translated = encrypt_message(key, message) elif mode == "decrypt": translated = decrypt_message(key, message) print(f"Using the key {key}, the {mode}ed message is: {translated}") if __name__ == "__main__": import doctest doctest.testmod() main()
usrbinenv python3 python program to translate to and from morse code https en wikipedia orgwikimorsecode fmt off fmt on encryptsos encryptsos encryptsos true decrypt sos s joinmorsecodedict decryptencrypts s true usr bin env python3 python program to translate to and from morse code https en wikipedia org wiki morse_code fmt off exclamation mark is not in itu r recommendation fmt on encrypt sos encrypt sos encrypt sos true decrypt sos s join morse_code_dict decrypt encrypt s s true
MORSE_CODE_DICT = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", '"': ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()} def encrypt(message: str) -> str: return " ".join(MORSE_CODE_DICT[char] for char in message.upper()) def decrypt(message: str) -> str: return "".join(REVERSE_DICT[char] for char in message.split()) def main() -> None: message = "Morse code here!" print(message) message = encrypt(message) print(message) message = decrypt(message) print(message) if __name__ == "__main__": main()
function to encrypt text using pseudorandom numbers onepad encrypt onepad encrypt random seed1 onepad encrypt 6969 69 random seed1 onepad encrypthello 9729 114756 4653 31309 10492 69 292 33 131 61 onepad encrypt1 traceback most recent call last typeerror int object is not iterable onepad encrypt1 1 traceback most recent call last typeerror float object is not iterable function to decrypt text using pseudorandom numbers onepad decrypt onepad decrypt35 onepad decrypt 35 traceback most recent call last indexerror list index out of range random seed1 onepad decrypt9729 114756 4653 31309 10492 69 292 33 131 61 hello function to encrypt text using pseudo random numbers onepad encrypt onepad encrypt random seed 1 onepad encrypt 6969 69 random seed 1 onepad encrypt hello 9729 114756 4653 31309 10492 69 292 33 131 61 onepad encrypt 1 traceback most recent call last typeerror int object is not iterable onepad encrypt 1 1 traceback most recent call last typeerror float object is not iterable function to decrypt text using pseudo random numbers onepad decrypt onepad decrypt 35 onepad decrypt 35 traceback most recent call last indexerror list index out of range random seed 1 onepad decrypt 9729 114756 4653 31309 10492 69 292 33 131 61 hello
import random class Onepad: @staticmethod def encrypt(text: str) -> tuple[list[int], list[int]]: plain = [ord(i) for i in text] key = [] cipher = [] for i in plain: k = random.randint(1, 300) c = (i + k) * k cipher.append(c) key.append(k) return cipher, key @staticmethod def decrypt(cipher: list[int], key: list[int]) -> str: plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(p)) return "".join(plain) if __name__ == "__main__": c, k = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
the permutation cipher also called the transposition cipher is a simple encryption technique that rearranges the characters in a message based on a secret key it divides the message into blocks and applies a permutation to the characters within each block according to the key the key is a sequence of unique integers that determine the order of character rearrangement for more info https www nku educhristensen140220permutation20ciphers pdf generate a valid block size that is a factor of the message length args messagelength int the length of the message returns int a valid block size example random seed1 generatevalidblocksize12 3 generate a random permutation key of a specified block size args blocksize int the size of each permutation block returns listint a list containing a random permutation of digits example random seed0 generatepermutationkey4 2 0 1 3 encrypt a message using a permutation cipher with block rearrangement using a key args message str the plaintext message to be encrypted key listint the permutation key for decryption blocksize int the size of each permutation block returns tuple a tuple containing the encrypted message and the encryption key example encryptedmessage key encrypthello world decryptedmessage decryptencryptedmessage key decryptedmessage hello world decrypt an encrypted message using a permutation cipher with block rearrangement args encryptedmessage str the encrypted message key listint the permutation key for decryption returns str the decrypted plaintext message example encryptedmessage key encrypthello world decryptedmessage decryptencryptedmessage key decryptedmessage hello world driver function to pass message to get encrypted then decrypted example main decrypted message hello world generate a valid block size that is a factor of the message length args message_length int the length of the message returns int a valid block size example random seed 1 generate_valid_block_size 12 3 generate a random permutation key of a specified block size args block_size int the size of each permutation block returns list int a list containing a random permutation of digits example random seed 0 generate_permutation_key 4 2 0 1 3 encrypt a message using a permutation cipher with block rearrangement using a key args message str the plaintext message to be encrypted key list int the permutation key for decryption block_size int the size of each permutation block returns tuple a tuple containing the encrypted message and the encryption key example encrypted_message key encrypt hello world decrypted_message decrypt encrypted_message key decrypted_message hello world decrypt an encrypted message using a permutation cipher with block rearrangement args encrypted_message str the encrypted message key list int the permutation key for decryption returns str the decrypted plaintext message example encrypted_message key encrypt hello world decrypted_message decrypt encrypted_message key decrypted_message hello world driver function to pass message to get encrypted then decrypted example main decrypted message hello world
import random def generate_valid_block_size(message_length: int) -> int: block_sizes = [ block_size for block_size in range(2, message_length + 1) if message_length % block_size == 0 ] return random.choice(block_sizes) def generate_permutation_key(block_size: int) -> list[int]: digits = list(range(block_size)) random.shuffle(digits) return digits def encrypt( message: str, key: list[int] | None = None, block_size: int | None = None ) -> tuple[str, list[int]]: message = message.upper() message_length = len(message) if key is None or block_size is None: block_size = generate_valid_block_size(message_length) key = generate_permutation_key(block_size) encrypted_message = "" for i in range(0, message_length, block_size): block = message[i : i + block_size] rearranged_block = [block[digit] for digit in key] encrypted_message += "".join(rearranged_block) return encrypted_message, key def decrypt(encrypted_message: str, key: list[int]) -> str: key_length = len(key) decrypted_message = "" for i in range(0, len(encrypted_message), key_length): block = encrypted_message[i : i + key_length] original_block = [""] * key_length for j, digit in enumerate(key): original_block[digit] = block[j] decrypted_message += "".join(original_block) return decrypted_message def main() -> None: message = "HELLO WORLD" encrypted_message, key = encrypt(message) decrypted_message = decrypt(encrypted_message, key) print(f"Decrypted message: {decrypted_message}") if __name__ == "__main__": import doctest doctest.testmod() main()
https en wikipedia orgwikiplayfaircipherdescription the playfair cipher was developed by charles wheatstone in 1854 it s use was heavily promotedby lord playfair hence its name some features of the playfair cipher are 1 it was the first literal diagram substitution cipher 2 it is a manual symmetric encryption technique 3 it is a multiple letter encryption cipher the implementation in the code below encodes alphabets only it removes spaces special characters and numbers from the code playfair is no longer used by military forces because of known insecurities and of the advent of automated encryption devices this cipher is regarded as insecure since before world war i prepare the plaintext by upcasing it and separating repeated letters with x s i and j are used interchangeably to allow us to use a 5x5 table 25 letters we re using a list instead of a 2d array because it makes the math for setting up the table and doing the actual encodingdecoding simpler copy key chars into the table if they are in alphabet ignoring duplicates fill the rest of the table in with the remaining alphabet chars encode the given plaintext using the playfair cipher takes the plaintext and the key as input and returns the encoded string encodehello monarchy cfsupm encodeattack on the left flank emergency dqzsbyfsdzfmfnlohfdrsg encodesorry special avxetx encodenumber 1 number umbenf encodephotosynthesis the sun oemhqhvchesuke decode the input string using the provided key decodebmzfazrzdh hazard firehazard decodehnbwbpqt automobile drivingx decodeslyssaqs castle atxtackx prepare the plaintext by up casing it and separating repeated letters with x s i and j are used interchangeably to allow us to use a 5x5 table 25 letters we re using a list instead of a 2d array because it makes the math for setting up the table and doing the actual encoding decoding simpler copy key chars into the table if they are in alphabet ignoring duplicates fill the rest of the table in with the remaining alphabet chars encode the given plaintext using the playfair cipher takes the plaintext and the key as input and returns the encoded string encode hello monarchy cfsupm encode attack on the left flank emergency dqzsbyfsdzfmfnlohfdrsg encode sorry special avxetx encode number 1 number umbenf encode photosynthesis the sun oemhqhvchesuke rectangle decode the input string using the provided key decode bmzfazrzdh hazard firehazard decode hnbwbpqt automobile drivingx decode slyssaqs castle atxtackx rectangle
import itertools import string from collections.abc import Generator, Iterable def chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...], None, None]: it = iter(seq) while True: chunk = tuple(itertools.islice(it, size)) if not chunk: return yield chunk def prepare_input(dirty: str) -> str: dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" if len(dirty) < 2: return dirty for i in range(len(dirty) - 1): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(clean) & 1: clean += "X" return clean def generate_table(key: str) -> list[str]: alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" table = [] for char in key.upper(): if char not in table and char in alphabet: table.append(char) for char in alphabet: if char not in table: table.append(char) return table def encode(plaintext: str, key: str) -> str: table = generate_table(key) plaintext = prepare_input(plaintext) ciphertext = "" for char1, char2 in chunker(plaintext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: ciphertext += table[row1 * 5 + (col1 + 1) % 5] ciphertext += table[row2 * 5 + (col2 + 1) % 5] elif col1 == col2: ciphertext += table[((row1 + 1) % 5) * 5 + col1] ciphertext += table[((row2 + 1) % 5) * 5 + col2] else: ciphertext += table[row1 * 5 + col2] ciphertext += table[row2 * 5 + col1] return ciphertext def decode(ciphertext: str, key: str) -> str: table = generate_table(key) plaintext = "" for char1, char2 in chunker(ciphertext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: plaintext += table[row1 * 5 + (col1 - 1) % 5] plaintext += table[row2 * 5 + (col2 - 1) % 5] elif col1 == col2: plaintext += table[((row1 - 1) % 5) * 5 + col1] plaintext += table[((row2 - 1) % 5) * 5 + col2] else: plaintext += table[row1 * 5 + col2] plaintext += table[row2 * 5 + col1] return plaintext if __name__ == "__main__": import doctest doctest.testmod() print("Encoded:", encode("BYE AND THANKS", "GREETING")) print("Decoded:", decode("CXRBANRLBALQ", "GREETING"))
usrbinenv python3 a polybius square is a table that allows someone to translate letters into numbers https www braingle combrainteaserscodespolybius php return the pair of numbers that represents the given letter in the polybius square np arrayequalpolybiuscipher lettertonumbers a 1 1 true np arrayequalpolybiuscipher lettertonumbers u 4 5 true return the letter corresponding to the position index1 index2 in the polybius square polybiuscipher numberstoletter4 5 u true polybiuscipher numberstoletter1 1 a true return the encoded version of message according to the polybius cipher polybiuscipher encodetest message 44154344 32154343112215 true polybiuscipher encodetest message 44154344 32154343112215 true return the decoded version of message according to the polybius cipher polybiuscipher decode44154344 32154343112215 test message true polybiuscipher decode4415434432154343112215 testmessage true usr bin env python3 a polybius square is a table that allows someone to translate letters into numbers https www braingle com brainteasers codes polybius php return the pair of numbers that represents the given letter in the polybius square np array_equal polybiuscipher letter_to_numbers a 1 1 true np array_equal polybiuscipher letter_to_numbers u 4 5 true return the letter corresponding to the position index1 index2 in the polybius square polybiuscipher numbers_to_letter 4 5 u true polybiuscipher numbers_to_letter 1 1 a true return the encoded version of message according to the polybius cipher polybiuscipher encode test message 44154344 32154343112215 true polybiuscipher encode test message 44154344 32154343112215 true return the decoded version of message according to the polybius cipher polybiuscipher decode 44154344 32154343112215 test message true polybiuscipher decode 4415434432154343112215 testmessage true
import numpy as np SQUARE = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] class PolybiusCipher: def __init__(self) -> None: self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: index1, index2 = np.where(letter == self.SQUARE) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: return self.SQUARE[index1 - 1, index2 - 1] def encode(self, message: str) -> str: message = message.lower() message = message.replace("j", "i") encoded_message = "" for letter_index in range(len(message)): if message[letter_index] != " ": numbers = self.letter_to_numbers(message[letter_index]) encoded_message = encoded_message + str(numbers[0]) + str(numbers[1]) elif message[letter_index] == " ": encoded_message = encoded_message + " " return encoded_message def decode(self, message: str) -> str: message = message.replace(" ", " ") decoded_message = "" for numbers_index in range(int(len(message) / 2)): if message[numbers_index * 2] != " ": index1 = message[numbers_index * 2] index2 = message[numbers_index * 2 + 1] letter = self.numbers_to_letter(int(index1), int(index2)) decoded_message = decoded_message + letter elif message[numbers_index * 2] == " ": decoded_message = decoded_message + " " return decoded_message
generatetable marvin doctest normalizewhitespace abcdefghijklm uvwxyznopqrst abcdefghijklm nopqrstuvwxyz abcdefghijklm stuvwxyznopqr abcdefghijklm qrstuvwxyznop abcdefghijklm wxyznopqrstuv abcdefghijklm uvwxyznopqrst encrypt marvin jessica qracrwu decrypt marvin qracrwu jessica getpositiongeneratetable marvin 0 m 0 12 char is either in the 0th row or the 1st row getopponentgeneratetable marvin 0 m t demo enter key marvin enter text to encrypt jessica encrypted qracrwu decrypted with key jessica generate_table marvin doctest normalize_whitespace abcdefghijklm uvwxyznopqrst abcdefghijklm nopqrstuvwxyz abcdefghijklm stuvwxyznopqr abcdefghijklm qrstuvwxyznop abcdefghijklm wxyznopqrstuv abcdefghijklm uvwxyznopqrst encrypt marvin jessica qracrwu decrypt marvin qracrwu jessica get_position generate_table marvin 0 m 0 12 char is either in the 0th row or the 1st row get_opponent generate_table marvin 0 m t fist ensure that all our tests are passing demo enter key marvin enter text to encrypt jessica encrypted qracrwu decrypted with key jessica
alphabet = { "A": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"), "B": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"), "C": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"), "D": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"), "E": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"), "F": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"), "G": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"), "H": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"), "I": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"), "J": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"), "K": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"), "L": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"), "M": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"), "N": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"), "O": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"), "P": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"), "Q": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"), "R": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"), "S": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"), "T": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"), "U": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"), "V": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"), "W": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"), "X": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"), "Y": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"), "Z": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"), } def generate_table(key: str) -> list[tuple[str, str]]: return [alphabet[char] for char in key.upper()] def encrypt(key: str, words: str) -> str: cipher = "" count = 0 table = generate_table(key) for char in words.upper(): cipher += get_opponent(table[count], char) count = (count + 1) % len(table) return cipher def decrypt(key: str, words: str) -> str: return encrypt(key, words) def get_position(table: tuple[str, str], char: str) -> tuple[int, int]: row = 0 if char in table[0] else 1 col = table[row].index(char) return row, col def get_opponent(table: tuple[str, str], char: str) -> str: row, col = get_position(table, char.upper()) if row == 1: return table[0][col] else: return table[1][col] if row == 0 else char if __name__ == "__main__": import doctest doctest.testmod() key = input("Enter key: ").strip() text = input("Enter text to encrypt: ").strip() cipher_text = encrypt(key, text) print(f"Encrypted: {cipher_text}") print(f"Decrypted with key: {decrypt(key, cipher_text)}")
primality testing with the rabinmiller algorithm primality testing with the rabin miller algorithm
import random def rabin_miller(num: int) -> bool: s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for _ in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: i = 0 while v != (num - 1): if i == t - 1: return False else: i = i + 1 v = (v**2) % num return True def is_prime_low_num(num: int) -> bool: if num < 2: return False low_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(num) def generate_large_prime(keysize: int = 1024) -> int: while True: num = random.randrange(2 ** (keysize - 1), 2 ** (keysize)) if is_prime_low_num(num): return num if __name__ == "__main__": num = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
https en wikipedia orgwikirailfencecipher def encryptinputstring str key int str tempgrid listliststr for in rangekey lowest key 1 if key 0 raise valueerrorheight of grid can t be 0 or negative if key 1 or leninputstring key return inputstring for position character in enumerateinputstring num position lowest 2 puts it in bounds num minnum lowest 2 num creates zigzag pattern tempgridnum appendcharacter grid joinrow for row in tempgrid outputstring joingrid return outputstring def decryptinputstring str key int str grid lowest key 1 if key 0 raise valueerrorheight of grid can t be 0 or negative if key 1 return inputstring tempgrid listliststr for in rangekey generates template for position in rangeleninputstring num position lowest 2 puts it in bounds num minnum lowest 2 num creates zigzag pattern tempgridnum append counter 0 for row in tempgrid fills in the characters splice inputstringcounter counter lenrow grid appendlistsplice counter lenrow outputstring reads as zigzag for position in rangeleninputstring num position lowest 2 puts it in bounds num minnum lowest 2 num creates zigzag pattern outputstring gridnum0 gridnum pop0 return outputstring def bruteforceinputstring str dictint str results for keyguess in range1 leninputstring tries every key resultskeyguess decryptinputstring keyguess return results if name main import doctest doctest testmod shuffles the character of a string by placing each of them in a grid the height is dependent on the key in a zigzag formation and reading it left to right encrypt hello world 4 hwe olordll encrypt this is a message 0 traceback most recent call last valueerror height of grid can t be 0 or negative encrypt b this is a byte string 5 traceback most recent call last typeerror sequence item 0 expected str instance int found puts it in bounds creates zigzag pattern generates a template based on the key and fills it in with the characters of the input string and then reading it in a zigzag formation decrypt hwe olordll 4 hello world decrypt this is a message 10 traceback most recent call last valueerror height of grid can t be 0 or negative decrypt my key is very big 100 my key is very big generates template puts it in bounds creates zigzag pattern fills in the characters reads as zigzag puts it in bounds creates zigzag pattern uses decrypt function by guessing every key bruteforce hwe olordll 4 hello world tries every key
def encrypt(input_string: str, key: int) -> str: temp_grid: list[list[str]] = [[] for _ in range(key)] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1 or len(input_string) <= key: return input_string for position, character in enumerate(input_string): num = position % (lowest * 2) num = min(num, lowest * 2 - num) temp_grid[num].append(character) grid = ["".join(row) for row in temp_grid] output_string = "".join(grid) return output_string def decrypt(input_string: str, key: int) -> str: grid = [] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1: return input_string temp_grid: list[list[str]] = [[] for _ in range(key)] for position in range(len(input_string)): num = position % (lowest * 2) num = min(num, lowest * 2 - num) temp_grid[num].append("*") counter = 0 for row in temp_grid: splice = input_string[counter : counter + len(row)] grid.append(list(splice)) counter += len(row) output_string = "" for position in range(len(input_string)): num = position % (lowest * 2) num = min(num, lowest * 2 - num) output_string += grid[num][0] grid[num].pop(0) return output_string def bruteforce(input_string: str) -> dict[int, str]: results = {} for key_guess in range(1, len(input_string)): results[key_guess] = decrypt(input_string, key_guess) return results if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikirot13 msg my secret bank account number is 17352946 so don t tell anyone s dencryptmsg s zl frperg onax nppbhag ahzore vf 17352946 fb qba g gryy nalbar dencrypts msg true https en wikipedia org wiki rot13 msg my secret bank account number is 173 52946 so don t tell anyone s dencrypt msg s zl frperg onax nppbhag ahzore vf 173 52946 fb qba g gryy nalbar dencrypt s msg true
def dencrypt(s: str, n: int = 13) -> str: out = "" for c in s: if "A" <= c <= "Z": out += chr(ord("A") + (ord(c) - ord("A") + n) % 26) elif "a" <= c <= "z": out += chr(ord("a") + (ord(c) - ord("a") + n) % 26) else: out += c return out def main() -> None: s0 = input("Enter message: ") s1 = dencrypt(s0, 13) print("Encryption:", s1) s2 = dencrypt(s1, 13) print("Decryption: ", s2) if __name__ == "__main__": import doctest doctest.testmod() main()
an rsa prime factor algorithm the program can efficiently factor rsa prime number given the private key d and public key e source on page 3 of https crypto stanford edudabopapersrsasurvey pdf more readable source https www dimgt com aursafactorizen html large number can take minutes to factor therefore are not included in doctest this function returns the factors of n where pqn return p q we call n the rsa modulus e the encryption exponent and d the decryption exponent the pair n e is the public key as its name suggests it is public and is used to encrypt messages the pair n d is the secret key or private key and is known only to the recipient of encrypted messages rsafactor3 16971 25777 149 173 rsafactor7331 11 27233 113 241 rsafactor4021 13 17711 89 199 this function returns the factors of n where p q n return p q we call n the rsa modulus e the encryption exponent and d the decryption exponent the pair n e is the public key as its name suggests it is public and is used to encrypt messages the pair n d is the secret key or private key and is known only to the recipient of encrypted messages rsafactor 3 16971 25777 149 173 rsafactor 7331 11 27233 113 241 rsafactor 4021 13 17711 89 199 find the correct factors t is not divisible by 2 break and choose another g
from __future__ import annotations import math import random def rsafactor(d: int, e: int, n: int) -> list[int]: k = d * e - 1 p = 0 q = 0 while p == 0: g = random.randint(2, n - 1) t = k while True: if t % 2 == 0: t = t // 2 x = (g**t) % n y = math.gcd(x - 1, n) if x > 1 and y > 1: p = y q = n // y break else: break return sorted([p, q]) if __name__ == "__main__": import doctest doctest.testmod()
random seed0 for repeatability publickey privatekey generatekey8 publickey 26569 239 privatekey 26569 2855 generate e that is relatively prime to p 1 q 1 calculate d that is mod inverse of e random seed 0 for repeatability public_key private_key generate_key 8 public_key 26569 239 private_key 26569 2855 generate e that is relatively prime to p 1 q 1 calculate d that is mod inverse of e
import os import random import sys from maths.greatest_common_divisor import gcd_by_iterative from . import cryptomath_module, rabin_miller def main() -> None: print("Making key files...") make_key_files("rsa", 1024) print("Key files generation successful.") def generate_key(key_size: int) -> tuple[tuple[int, int], tuple[int, int]]: p = rabin_miller.generate_large_prime(key_size) q = rabin_miller.generate_large_prime(key_size) n = p * q while True: e = random.randrange(2 ** (key_size - 1), 2 ** (key_size)) if gcd_by_iterative(e, (p - 1) * (q - 1)) == 1: break d = cryptomath_module.find_mod_inverse(e, (p - 1) * (q - 1)) public_key = (n, e) private_key = (n, d) return (public_key, private_key) def make_key_files(name: str, key_size: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." ) sys.exit() public_key, private_key = generate_key(key_size) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as out_file: out_file.write(f"{key_size},{public_key[0]},{public_key[1]}") print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as out_file: out_file.write(f"{key_size},{private_key[0]},{private_key[1]}") if __name__ == "__main__": main()
this algorithm uses the caesar cipher algorithm but removes the option to use brute force to decrypt the message the passcode is a random password from the selection buffer of 1 uppercase letters of the english alphabet 2 lowercase letters of the english alphabet 3 digits from 0 to 9 using unique characters from the passcode the normal list of characters that can be allowed in the plaintext is pivoted and shuffled refer to docstring of makekeylist to learn more about the shuffling then using the passcode a number is calculated which is used to encrypt the plaintext message with the normal shift cipher method only in this case the reference to look back at while decrypting is shuffled each cipher object can possess an optional argument as passcode without which a new passcode is generated for that object automatically cip1 shuffledshiftcipher d4usr9twxw9wmd cip2 shuffledshiftcipher initializes a cipher object with a passcode as it s entity note no new passcode is generated if user provides a passcode while creating the object return passcode of the cipher object mutates the list by changing the sign of each alternate element param iterlist takes a list iterable return the mutated list creates a random password from the selection buffer of 1 uppercase letters of the english alphabet 2 lowercase letters of the english alphabet 3 digits from 0 to 9 rtype list return a password of a random length between 10 to 20 shuffles the ordered character choices by pivoting at breakpoints breakpoints are the set of characters in the passcode eg if abcdefghijklmnopqrstuvwxyz are the possible characters and camera is the passcode then breakpoints a c e m r sorted set of characters from passcode shuffled parts a cb ed mlkjihgf rqpon zyxwvuts shuffled keylist acbedmlkjihgfrqponzyxwvuts shuffling only 26 letters of the english alphabet can generate 26 combinations for the shuffled list in the program we consider a set of 97 characters including letters digits punctuation and whitespaces thereby creating a possibility of 97 combinations which is a 152 digit number in itself thus diminishing the possibility of a brute force approach moreover shift keys even introduce a multiple of 26 for a brute force approach for each of the already 97 combinations keylistoptions contain nearly all printable except few elements from string whitespace creates points known as breakpoints to break the keylistoptions at those points and pivot each substring algorithm for creating a new shuffled list keysl out of keylistoptions checking breakpoints at which to pivot temporary sublist and add it into keysl returning a shuffled keysl to prevent brute force guessing of shift key sum of the mutated list of ascii values of all characters where the mutated list is the one returned by negpos performs shifting of the encodedmessage w r t the shuffled keylist to create the decodedmessage ssc shuffledshiftcipher 4pyixyqeqzr44 ssc decryptd1z6 5z 5z z zp 5 z hello this is a modified caesar cipher decoding shift like caesar cipher algorithm implementing negative shift or reverse shift or left shift performs shifting of the plaintext w r t the shuffled keylist to create the encodedmessage ssc shuffledshiftcipher 4pyixyqeqzr44 ssc encrypt hello this is a modified caesar cipher d1z6 5z 5z z zp 5 z encoding shift like caesar cipher algorithm implementing positive shift or forward shift or right shift testendtoend hello this is a modified caesar cipher this algorithm uses the caesar cipher algorithm but removes the option to use brute force to decrypt the message the passcode is a random password from the selection buffer of 1 uppercase letters of the english alphabet 2 lowercase letters of the english alphabet 3 digits from 0 to 9 using unique characters from the passcode the normal list of characters that can be allowed in the plaintext is pivoted and shuffled refer to docstring of __make_key_list to learn more about the shuffling then using the passcode a number is calculated which is used to encrypt the plaintext message with the normal shift cipher method only in this case the reference to look back at while decrypting is shuffled each cipher object can possess an optional argument as passcode without which a new passcode is generated for that object automatically cip1 shuffledshiftcipher d4usr9twxw9wmd cip2 shuffledshiftcipher initializes a cipher object with a passcode as it s entity note no new passcode is generated if user provides a passcode while creating the object return passcode of the cipher object mutates the list by changing the sign of each alternate element param iterlist takes a list iterable return the mutated list creates a random password from the selection buffer of 1 uppercase letters of the english alphabet 2 lowercase letters of the english alphabet 3 digits from 0 to 9 rtype list return a password of a random length between 10 to 20 shuffles the ordered character choices by pivoting at breakpoints breakpoints are the set of characters in the passcode eg if abcdefghijklmnopqrstuvwxyz are the possible characters and camera is the passcode then breakpoints a c e m r sorted set of characters from passcode shuffled parts a cb ed mlkjihgf rqpon zyxwvuts shuffled __key_list acbedmlkjihgfrqponzyxwvuts shuffling only 26 letters of the english alphabet can generate 26 combinations for the shuffled list in the program we consider a set of 97 characters including letters digits punctuation and whitespaces thereby creating a possibility of 97 combinations which is a 152 digit number in itself thus diminishing the possibility of a brute force approach moreover shift keys even introduce a multiple of 26 for a brute force approach for each of the already 97 combinations key_list_options contain nearly all printable except few elements from string whitespace creates points known as breakpoints to break the key_list_options at those points and pivot each substring algorithm for creating a new shuffled list keys_l out of key_list_options checking breakpoints at which to pivot temporary sublist and add it into keys_l returning a shuffled keys_l to prevent brute force guessing of shift key sum of the mutated list of ascii values of all characters where the mutated list is the one returned by __neg_pos performs shifting of the encoded_message w r t the shuffled __key_list to create the decoded_message ssc shuffledshiftcipher 4pyixyqeqzr44 ssc decrypt d 1z6 5z 5z z zp 5 z hello this is a modified caesar cipher decoding shift like caesar cipher algorithm implementing negative shift or reverse shift or left shift performs shifting of the plaintext w r t the shuffled __key_list to create the encoded_message ssc shuffledshiftcipher 4pyixyqeqzr44 ssc encrypt hello this is a modified caesar cipher d 1z6 5z 5z z zp 5 z encoding shift like caesar cipher algorithm implementing positive shift or forward shift or right shift test_end_to_end hello this is a modified caesar cipher
from __future__ import annotations import random import string class ShuffledShiftCipher: def __init__(self, passcode: str | None = None) -> None: self.__passcode = passcode or self.__passcode_creator() self.__key_list = self.__make_key_list() self.__shift_key = self.__make_shift_key() def __str__(self) -> str: return "".join(self.__passcode) def __neg_pos(self, iterlist: list[int]) -> list[int]: for i in range(1, len(iterlist), 2): iterlist[i] *= -1 return iterlist def __passcode_creator(self) -> list[str]: choices = string.ascii_letters + string.digits password = [random.choice(choices) for _ in range(random.randint(10, 20))] return password def __make_key_list(self) -> list[str]: key_list_options = ( string.ascii_letters + string.digits + string.punctuation + " \t\n" ) keys_l = [] breakpoints = sorted(set(self.__passcode)) temp_list: list[str] = [] for i in key_list_options: temp_list.extend(i) if i in breakpoints or i == key_list_options[-1]: keys_l.extend(temp_list[::-1]) temp_list.clear() return keys_l def __make_shift_key(self) -> int: num = sum(self.__neg_pos([ord(x) for x in self.__passcode])) return num if num > 0 else len(self.__passcode) def decrypt(self, encoded_message: str) -> str: decoded_message = "" for i in encoded_message: position = self.__key_list.index(i) decoded_message += self.__key_list[ (position - self.__shift_key) % -len(self.__key_list) ] return decoded_message def encrypt(self, plaintext: str) -> str: encoded_message = "" for i in plaintext: position = self.__key_list.index(i) encoded_message += self.__key_list[ (position + self.__shift_key) % len(self.__key_list) ] return encoded_message def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str: cip1 = ShuffledShiftCipher() return cip1.decrypt(cip1.encrypt(msg)) if __name__ == "__main__": import doctest doctest.testmod()
removes duplicate alphabetic characters in a keyword letter is ignored after its first appearance param key keyword to use return string with duplicates removed removeduplicates hello world helo wrd returns a cipher map given a keyword param key keyword to use return dictionary cipher map create a list of the letters in the alphabet remove duplicate characters from key first fill cipher with key characters then map remaining characters in alphabet to the alphabet from the beginning ensure we are not mapping letters to letters previously mapped enciphers a message given a cipher map param message message to encipher param ciphermap cipher map return enciphered string encipher hello world createciphermap goodbye cyjjm vmqjb deciphers a message given a cipher map param message message to decipher param ciphermap dictionary mapping to use return deciphered string ciphermap createciphermap goodbye decipherencipher hello world ciphermap ciphermap hello world reverse our cipher mappings handles io return void removes duplicate alphabetic characters in a keyword letter is ignored after its first appearance param key keyword to use return string with duplicates removed remove_duplicates hello world helo wrd returns a cipher map given a keyword param key keyword to use return dictionary cipher map create a list of the letters in the alphabet remove duplicate characters from key first fill cipher with key characters then map remaining characters in alphabet to the alphabet from the beginning ensure we are not mapping letters to letters previously mapped enciphers a message given a cipher map param message message to encipher param cipher_map cipher map return enciphered string encipher hello world create_cipher_map goodbye cyjjm vmqjb deciphers a message given a cipher map param message message to decipher param cipher_map dictionary mapping to use return deciphered string cipher_map create_cipher_map goodbye decipher encipher hello world cipher_map cipher_map hello world reverse our cipher mappings handles i o return void
def remove_duplicates(key: str) -> str: key_no_dups = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def create_cipher_map(key: str) -> dict[str, str]: alphabet = [chr(i + 65) for i in range(26)] key = remove_duplicates(key.upper()) offset = len(key) cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)} for i in range(len(cipher_alphabet), 26): char = alphabet[i - offset] while char in key: offset -= 1 char = alphabet[i - offset] cipher_alphabet[alphabet[i]] = char return cipher_alphabet def encipher(message: str, cipher_map: dict[str, str]) -> str: return "".join(cipher_map.get(ch, ch) for ch in message.upper()) def decipher(message: str, cipher_map: dict[str, str]) -> str: rev_cipher_map = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper()) def main() -> None: message = input("Enter message to encode or decode: ").strip() key = input("Enter keyword: ").strip() option = input("Encipher or decipher? E/D:").strip()[0].lower() try: func = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option") cipher_map = create_cipher_map(key) print(func(message, cipher_map)) if __name__ == "__main__": import doctest doctest.testmod() main()
encryptmessage lfwoayuisvkmnxpbdcrjtqeghz harshil darji ilcrism olcvs decryptmessage lfwoayuisvkmnxpbdcrjtqeghz ilcrism olcvs harshil darji encrypt_message lfwoayuisvkmnxpbdcrjtqeghz harshil darji ilcrism olcvs decrypt_message lfwoayuisvkmnxpbdcrjtqeghz ilcrism olcvs harshil darji
import random import sys LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = "LFWOAYUISVKMNXPBDCRJTQEGHZ" resp = input("Encrypt/Decrypt [e/d]: ") check_valid_key(key) if resp.lower().startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif resp.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ion: \n{translated}") def check_valid_key(key: str) -> None: key_list = list(key) letters_list = list(LETTERS) key_list.sort() letters_list.sort() if key_list != letters_list: sys.exit("Error in the key or symbol set.") def encrypt_message(key: str, message: str) -> str: return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: return translate_message(key, message, "decrypt") def translate_message(key: str, message: str, mode: str) -> str: translated = "" chars_a = LETTERS chars_b = key if mode == "decrypt": chars_a, chars_b = chars_b, chars_a for symbol in message: if symbol.upper() in chars_a: sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: translated += symbol return translated def get_random_key() -> str: key = list(LETTERS) random.shuffle(key) return "".join(key) if __name__ == "__main__": main()
in cryptography the transposition cipher is a method of encryption where the positions of plaintext are shifted a certain numberdetermined by the key that follows a regular system that results in the permuted text known as the encrypted text the type of transposition cipher demonstrated under is the route cipher append pipe symbol vertical bar to identify spaces at the end encryptmessage6 harshil darji hlia rdsahrij decryptmessage6 hlia rdsahrij harshil darji in cryptography the transposition cipher is a method of encryption where the positions of plaintext are shifted a certain number determined by the key that follows a regular system that results in the permuted text known as the encrypted text the type of transposition cipher demonstrated under is the route cipher append pipe symbol vertical bar to identify spaces at the end encrypt_message 6 harshil darji hlia rdsahrij decrypt_message 6 hlia rdsahrij harshil darji
import math def main() -> None: message = input("Enter message: ") key = int(input(f"Enter key [2-{len(message) - 1}]: ")) mode = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): text = encrypt_message(key, message) elif mode.lower().startswith("d"): text = decrypt_message(key, message) print(f"Output:\n{text + '|'}") def encrypt_message(key: int, message: str) -> str: cipher_text = [""] * key for col in range(key): pointer = col while pointer < len(message): cipher_text[col] += message[pointer] pointer += key return "".join(cipher_text) def decrypt_message(key: int, message: str) -> str: num_cols = math.ceil(len(message) / key) num_rows = key num_shaded_boxes = (num_cols * num_rows) - len(message) plain_text = [""] * num_cols col = 0 row = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): col = 0 row += 1 return "".join(plain_text) if __name__ == "__main__": import doctest doctest.testmod() main()
the trifid cipher uses a table to fractionate each plaintext letter into a trigram mixes the constituents of the trigrams and then applies the table in reverse to turn these mixed trigrams into ciphertext letters https en wikipedia orgwikitrifidcipher fmt off fmt off arrange the triagram value of each letter of messagepart vertically and join them horizontally encryptpart ask testcharactertonumber 132111112 convert each letter of the input string into their respective trigram values join them and split them into three equal groups of strings which are returned decryptpart abcde testcharactertonumber 11111 21131 21122 a helper function that generates the triagrams and assigns each letter of the alphabet to its corresponding triagram and stores this in a dictionary charactertonumber and numbertocharacter after confirming if the alphabet s length is 27 test prepare i am a boy abcdefghijklmnopqrstuvwxyz expected iamaboy abcdefghijklmnopqrstuvwxyz testcharactertonumber testnumbertocharacter test expected true testing with incomplete alphabet prepare i am a boy abcdefghijklmnopqrstuvw traceback most recent call last keyerror length of alphabet has to be 27 testing with extra long alphabets prepare i am a boy abcdefghijklmnopqrstuvwxyzzwwtyyujjgfd traceback most recent call last keyerror length of alphabet has to be 27 testing with punctuations that are not in the given alphabet prepare am i a boy abcdefghijklmnopqrstuvwxyz traceback most recent call last valueerror each message character has to be included in alphabet testing with numbers prepare500 abcdefghijklmnopqrstuvwxyz traceback most recent call last attributeerror int object has no attribute replace validate message and alphabet set to upper and remove spaces check length and characters generate dictionares encryptmessage encrypts a message using the trifidcipher any punctuatuions that would be used should be added to the alphabet parameters message the message you want to encrypt alphabet optional the characters to be used for the cipher period optional the number of characters you want in a group whilst encrypting encryptmessage i am a boy bcdgbqy encryptmessage encryptmessage aide toi le c iel ta id era felixmardstbcghjknopquvwyz 5 fmjfvoissuftfpufeqqc decryptmessage decrypts a trifidcipher encrypted message parameters message the message you want to decrypt alphabet optional the characters used for the cipher period optional the number of characters used in grouping when it was encrypted decryptmessage bcdgbqy iamaboy decrypting with your own alphabet and period decryptmessage fmjfvoissuftfpufeqqc felixmardstbcghjknopquvwyz 5 aidetoilecieltaidera fmt off fmt off arrange the triagram value of each letter of message_part vertically and join them horizontally __encrypt_part ask test_character_to_number 132111112 convert each letter of the input string into their respective trigram values join them and split them into three equal groups of strings which are returned __decrypt_part abcde test_character_to_number 11111 21131 21122 a helper function that generates the triagrams and assigns each letter of the alphabet to its corresponding triagram and stores this in a dictionary character_to_number and number_to_character after confirming if the alphabet s length is 27 test __prepare i am a boy abcdefghijklmnopqrstuvwxyz expected iamaboy abcdefghijklmnopqrstuvwxyz test_character_to_number test_number_to_character test expected true testing with incomplete alphabet __prepare i am a boy abcdefghijklmnopqrstuvw traceback most recent call last keyerror length of alphabet has to be 27 testing with extra long alphabets __prepare i am a boy abcdefghijklmnopqrstuvwxyzzwwtyyujjgfd traceback most recent call last keyerror length of alphabet has to be 27 testing with punctuations that are not in the given alphabet __prepare am i a boy abcdefghijklmnopqrstuvwxyz traceback most recent call last valueerror each message character has to be included in alphabet testing with numbers __prepare 500 abcdefghijklmnopqrstuvwxyz traceback most recent call last attributeerror int object has no attribute replace validate message and alphabet set to upper and remove spaces check length and characters generate dictionares encrypt_message encrypts a message using the trifid_cipher any punctuatuions that would be used should be added to the alphabet parameters message the message you want to encrypt alphabet optional the characters to be used for the cipher period optional the number of characters you want in a group whilst encrypting encrypt_message i am a boy bcdgbqy encrypt_message encrypt_message aide toi le c iel ta id era felixmardstbcghjknopquvwyz 5 fmjfvoissuftfpufeqqc decrypt_message decrypts a trifid_cipher encrypted message parameters message the message you want to decrypt alphabet optional the characters used for the cipher period optional the number of characters used in grouping when it was encrypted decrypt_message bcdgbqy iamaboy decrypting with your own alphabet and period decrypt_message fmjfvoissuftfpufeqqc felixmardstbcghjknopquvwyz 5 aidetoilecieltaidera
from __future__ import annotations TEST_CHARACTER_TO_NUMBER = { "A": "111", "B": "112", "C": "113", "D": "121", "E": "122", "F": "123", "G": "131", "H": "132", "I": "133", "J": "211", "K": "212", "L": "213", "M": "221", "N": "222", "O": "223", "P": "231", "Q": "232", "R": "233", "S": "311", "T": "312", "U": "313", "V": "321", "W": "322", "X": "323", "Y": "331", "Z": "332", "+": "333", } TEST_NUMBER_TO_CHARACTER = {val: key for key, val in TEST_CHARACTER_TO_NUMBER.items()} def __encrypt_part(message_part: str, character_to_number: dict[str, str]) -> str: one, two, three = "", "", "" for each in (character_to_number[character] for character in message_part): one += each[0] two += each[1] three += each[2] return one + two + three def __decrypt_part( message_part: str, character_to_number: dict[str, str] ) -> tuple[str, str, str]: this_part = "".join(character_to_number[character] for character in message_part) result = [] tmp = "" for digit in this_part: tmp += digit if len(tmp) == len(message_part): result.append(tmp) tmp = "" return result[0], result[1], result[2] def __prepare( message: str, alphabet: str ) -> tuple[str, str, dict[str, str], dict[str, str]]: alphabet = alphabet.replace(" ", "").upper() message = message.replace(" ", "").upper() if len(alphabet) != 27: raise KeyError("Length of alphabet has to be 27.") if any(char not in alphabet for char in message): raise ValueError("Each message character has to be included in alphabet!") character_to_number = dict(zip(alphabet, TEST_CHARACTER_TO_NUMBER.values())) number_to_character = { number: letter for letter, number in character_to_number.items() } return message, alphabet, character_to_number, number_to_character def encrypt_message( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character_to_number, number_to_character = __prepare( message, alphabet ) encrypted_numeric = "" for i in range(0, len(message) + 1, period): encrypted_numeric += __encrypt_part( message[i : i + period], character_to_number ) encrypted = "" for i in range(0, len(encrypted_numeric), 3): encrypted += number_to_character[encrypted_numeric[i : i + 3]] return encrypted def decrypt_message( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character_to_number, number_to_character = __prepare( message, alphabet ) decrypted_numeric = [] for i in range(0, len(message), period): a, b, c = __decrypt_part(message[i : i + period], character_to_number) for j in range(len(a)): decrypted_numeric.append(a[j] + b[j] + c[j]) return "".join(number_to_character[each] for each in decrypted_numeric) if __name__ == "__main__": import doctest doctest.testmod() msg = "DEFEND THE EAST WALL OF THE CASTLE." encrypted = encrypt_message(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") decrypted = decrypt_message(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}")
vernamencrypthello key rijvs vernamdecryptrijvs key hello example usage vernam_encrypt hello key rijvs vernam_decrypt rijvs key hello example usage
def vernam_encrypt(plaintext: str, key: str) -> str: ciphertext = "" for i in range(len(plaintext)): ct = ord(key[i % len(key)]) - 65 + ord(plaintext[i]) - 65 while ct > 25: ct = ct - 26 ciphertext += chr(65 + ct) return ciphertext def vernam_decrypt(ciphertext: str, key: str) -> str: decrypted_text = "" for i in range(len(ciphertext)): ct = ord(ciphertext[i]) - ord(key[i % len(key)]) while ct < 0: ct = 26 + ct decrypted_text += chr(65 + ct) return decrypted_text if __name__ == "__main__": from doctest import testmod testmod() plaintext = "HELLO" key = "KEY" encrypted_text = vernam_encrypt(plaintext, key) decrypted_text = vernam_decrypt(encrypted_text, key) print("\n\n") print("Plaintext:", plaintext) print("Encrypted:", encrypted_text) print("Decrypted:", decrypted_text)
encryptmessage hdarji this is harshil darji from dharmaj akij ra odrjqqs gaisq muod mphumrs decryptmessage hdarji akij ra odrjqqs gaisq muod mphumrs this is harshil darji from dharmaj encrypt_message hdarji this is harshil darji from dharmaj akij ra odrjqqs gaisq muod mphumrs decrypt_message hdarji akij ra odrjqqs gaisq muod mphumrs this is harshil darji from dharmaj
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = input("Enter key [alphanumeric]: ") mode = input("Encrypt/Decrypt [e/d]: ") if mode.lower().startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif mode.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ed message:") print(translated) def encrypt_message(key: str, message: str) -> str: return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: return translate_message(key, message, "decrypt") def translate_message(key: str, message: str, mode: str) -> str: translated = [] key_index = 0 key = key.upper() for symbol in message: num = LETTERS.find(symbol.upper()) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index]) elif mode == "decrypt": num -= LETTERS.find(key[key_index]) num %= len(LETTERS) if symbol.isupper(): translated.append(LETTERS[num]) elif symbol.islower(): translated.append(LETTERS[num].lower()) key_index += 1 if key_index == len(key): key_index = 0 else: translated.append(symbol) return "".join(translated) if __name__ == "__main__": main()
christian bender date 21 12 2017 class xorcipher this class implements the xorcipher algorithm and provides some useful methods for encrypting and decrypting strings and files overview about methods encrypt list of char decrypt list of char encryptstring str decryptstring str encryptfile boolean decryptfile boolean simple constructor that receives a key or uses default key 0 private field input content of type string and key of type int output encrypted string content as a list of chars if key not passed the method uses the key by the constructor otherwise key 1 empty list xorcipher encrypt 5 one key xorcipher encrypthallo welt 1 i m m n v d m u normal key xorcipher encrypthallo welt 32 h a l l o x00 w e l t key greater than 255 xorcipher encrypthallo welt 256 h a l l o w e l t precondition make sure key is an appropriate size input content of type list and key of type int output decrypted string content as a list of chars if key not passed the method uses the key by the constructor otherwise key 1 empty list xorcipher decrypt 5 one key xorcipher decrypthallo welt 1 i m m n v d m u normal key xorcipher decrypthallo welt 32 h a l l o x00 w e l t key greater than 255 xorcipher decrypthallo welt 256 h a l l o w e l t precondition make sure key is an appropriate size input content of type string and key of type int output encrypted string content if key not passed the method uses the key by the constructor otherwise key 1 empty list xorcipher encryptstring 5 one key xorcipher encryptstringhallo welt 1 immn vdmu normal key xorcipher encryptstringhallo welt 32 hallox00welt key greater than 255 xorcipher encryptstringhallo welt 256 hallo welt precondition make sure key is an appropriate size this will be returned input content of type string and key of type int output decrypted string content if key not passed the method uses the key by the constructor otherwise key 1 empty list xorcipher decryptstring 5 one key xorcipher decryptstringhallo welt 1 immn vdmu normal key xorcipher decryptstringhallo welt 32 hallox00welt key greater than 255 xorcipher decryptstringhallo welt 256 hallo welt precondition make sure key is an appropriate size this will be returned input filename str and a key int output returns true if encrypt process was successful otherwise false if key not passed the method uses the key by the constructor otherwise key 1 precondition make sure key is an appropriate size actual encryptprocess input filename str and a key int output returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor otherwise key 1 precondition make sure key is an appropriate size actual encryptprocess tests crypt xorcipher key 67 test encrypt printcrypt encrypthallo welt key test decrypt printcrypt decryptcrypt encrypthallo welt key key test encryptstring printcrypt encryptstringhallo welt key test decryptstring printcrypt decryptstringcrypt encryptstringhallo welt key key if crypt encryptfiletest txt key printencrypt successful else printencrypt unsuccessful if crypt decryptfileencrypt out key printdecrypt successful else printdecrypt unsuccessful simple constructor that receives a key or uses default key 0 private field input content of type string and key of type int output encrypted string content as a list of chars if key not passed the method uses the key by the constructor otherwise key 1 empty list xorcipher encrypt 5 one key xorcipher encrypt hallo welt 1 i m m n v d m u normal key xorcipher encrypt hallo welt 32 h a l l o x00 w e l t key greater than 255 xorcipher encrypt hallo welt 256 h a l l o w e l t precondition make sure key is an appropriate size input content of type list and key of type int output decrypted string content as a list of chars if key not passed the method uses the key by the constructor otherwise key 1 empty list xorcipher decrypt 5 one key xorcipher decrypt hallo welt 1 i m m n v d m u normal key xorcipher decrypt hallo welt 32 h a l l o x00 w e l t key greater than 255 xorcipher decrypt hallo welt 256 h a l l o w e l t precondition make sure key is an appropriate size input content of type string and key of type int output encrypted string content if key not passed the method uses the key by the constructor otherwise key 1 empty list xorcipher encrypt_string 5 one key xorcipher encrypt_string hallo welt 1 i mmn vdmu normal key xorcipher encrypt_string hallo welt 32 hallo x00welt key greater than 255 xorcipher encrypt_string hallo welt 256 hallo welt precondition make sure key is an appropriate size this will be returned input content of type string and key of type int output decrypted string content if key not passed the method uses the key by the constructor otherwise key 1 empty list xorcipher decrypt_string 5 one key xorcipher decrypt_string hallo welt 1 i mmn vdmu normal key xorcipher decrypt_string hallo welt 32 hallo x00welt key greater than 255 xorcipher decrypt_string hallo welt 256 hallo welt precondition make sure key is an appropriate size this will be returned input filename str and a key int output returns true if encrypt process was successful otherwise false if key not passed the method uses the key by the constructor otherwise key 1 precondition make sure key is an appropriate size actual encrypt process input filename str and a key int output returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor otherwise key 1 precondition make sure key is an appropriate size actual encrypt process tests crypt xorcipher key 67 test encrypt print crypt encrypt hallo welt key test decrypt print crypt decrypt crypt encrypt hallo welt key key test encrypt_string print crypt encrypt_string hallo welt key test decrypt_string print crypt decrypt_string crypt encrypt_string hallo welt key key if crypt encrypt_file test txt key print encrypt successful else print encrypt unsuccessful if crypt decrypt_file encrypt out key print decrypt successful else print decrypt unsuccessful
from __future__ import annotations class XORCipher: def __init__(self, key: int = 0): self.__key = key def encrypt(self, content: str, key: int) -> list[str]: assert isinstance(key, int) assert isinstance(content, str) key = key or self.__key or 1 key %= 256 return [chr(ord(ch) ^ key) for ch in content] def decrypt(self, content: str, key: int) -> list[str]: assert isinstance(key, int) assert isinstance(content, str) key = key or self.__key or 1 key %= 256 return [chr(ord(ch) ^ key) for ch in content] def encrypt_string(self, content: str, key: int = 0) -> str: assert isinstance(key, int) assert isinstance(content, str) key = key or self.__key or 1 key %= 256 ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def decrypt_string(self, content: str, key: int = 0) -> str: assert isinstance(key, int) assert isinstance(content, str) key = key or self.__key or 1 key %= 256 ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def encrypt_file(self, file: str, key: int = 0) -> bool: assert isinstance(file, str) assert isinstance(key, int) key %= 256 try: with open(file) as fin, open("encrypt.out", "w+") as fout: for line in fin: fout.write(self.encrypt_string(line, key)) except OSError: return False return True def decrypt_file(self, file: str, key: int) -> bool: assert isinstance(file, str) assert isinstance(key, int) key %= 256 try: with open(file) as fin, open("decrypt.out", "w+") as fout: for line in fin: fout.write(self.decrypt_string(line, key)) except OSError: return False return True if __name__ == "__main__": from doctest import testmod testmod()
https en wikipedia orgwikiburrowse28093wheelertransform the burrowswheeler transform bwt also called blocksorting compression rearranges a character string into runs of similar characters this is useful for compression since it tends to be easy to compress a string that has runs of repeated characters by techniques such as movetofront transform and runlength encoding more importantly the transformation is reversible without needing to store any additional data except the position of the first original character the bwt is thus a free method of improving the efficiency of text compression algorithms costing only some extra computation param s the string that will be rotated lens times return a list with the rotations raises typeerror if s is not an instance of str examples allrotationsbanana doctest normalizewhitespace banana banana ananab nanaba anaban nabana abanan banana allrotationsaasadacasa doctest normalizewhitespace aasadacasa asadacasaa asadacasaa sadacasaaa adacasaaas dacasaaasa dacasaaasa acasaaasad casaaasada casaaasada asaaasadac saaasadaca aaasadacas allrotationspanamabanana doctest normalizewhitespace panamabanana anamabananap namabananapa amabananapan mabananapana abananapanam bananapanama ananapanamab nanapanamaba anapanamaban napanamabana apanamabanan allrotations5 traceback most recent call last typeerror the parameter s type must be str param s the string that will be used at bwt algorithm return the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list raises typeerror if the s parameter type is not str raises valueerror if the s parameter is empty examples bwttransformbanana bwtstring bnnaaa idxoriginalstring 6 bwttransformaasadacasa bwtstring aaaadsscaa idxoriginalstring 3 bwttransformpanamabanana bwtstring mnpbnnaaaaaa idxoriginalstring 11 bwttransform4 traceback most recent call last typeerror the parameter s type must be str bwttransform traceback most recent call last valueerror the parameter s must not be empty make a string composed of the last char of each rotation param bwtstring the string returned from bwt algorithm execution param idxoriginalstring a 0based index of the string that was used to generate bwtstring at ordered rotations list return the string used to generate bwtstring when bwt was executed raises typeerror if the bwtstring parameter type is not str raises valueerror if the bwtstring parameter is empty raises typeerror if the idxoriginalstring type is not int or if not possible to cast it to int raises valueerror if the idxoriginalstring value is lower than 0 or greater than lenbwtstring 1 reversebwtbnnaaa 6 banana reversebwtaaaadsscaa 3 aasadacasa reversebwtmnpbnnaaaaaa 11 panamabanana reversebwt4 11 traceback most recent call last typeerror the parameter bwtstring type must be str reversebwt 11 traceback most recent call last valueerror the parameter bwtstring must not be empty reversebwtmnpbnnaaaaaa asd doctest normalizewhitespace traceback most recent call last typeerror the parameter idxoriginalstring type must be int or passive of cast to int reversebwtmnpbnnaaaaaa 1 traceback most recent call last valueerror the parameter idxoriginalstring must not be lower than 0 reversebwtmnpbnnaaaaaa 12 doctest normalizewhitespace traceback most recent call last valueerror the parameter idxoriginalstring must be lower than lenbwtstring reversebwtmnpbnnaaaaaa 11 0 panamabanana reversebwtmnpbnnaaaaaa 11 4 panamabanana param s the string that will be rotated len s times return a list with the rotations raises typeerror if s is not an instance of str examples all_rotations banana doctest normalize_whitespace banana banana anana b nana ba ana ban na bana a banan banana all_rotations a_asa_da_casa doctest normalize_whitespace a_asa_da_casa _asa_da_casaa asa_da_casaa_ sa_da_casaa_a a_da_casaa_as _da_casaa_asa da_casaa_asa_ a_casaa_asa_d _casaa_asa_da casaa_asa_da_ asaa_asa_da_c saa_asa_da_ca aa_asa_da_cas all_rotations panamabanana doctest normalize_whitespace panamabanana anamabananap namabananapa amabananapan mabananapana abananapanam bananapanama ananapanamab nanapanamaba anapanamaban napanamabana apanamabanan all_rotations 5 traceback most recent call last typeerror the parameter s type must be str param s the string that will be used at bwt algorithm return the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list raises typeerror if the s parameter type is not str raises valueerror if the s parameter is empty examples bwt_transform banana bwt_string bnn aaa idx_original_string 6 bwt_transform a_asa_da_casa bwt_string aaaadss_c__aa idx_original_string 3 bwt_transform panamabanana bwt_string mnpbnnaaaaaa idx_original_string 11 bwt_transform 4 traceback most recent call last typeerror the parameter s type must be str bwt_transform traceback most recent call last valueerror the parameter s must not be empty sort the list of rotations in alphabetically order make a string composed of the last char of each rotation param bwt_string the string returned from bwt algorithm execution param idx_original_string a 0 based index of the string that was used to generate bwt_string at ordered rotations list return the string used to generate bwt_string when bwt was executed raises typeerror if the bwt_string parameter type is not str raises valueerror if the bwt_string parameter is empty raises typeerror if the idx_original_string type is not int or if not possible to cast it to int raises valueerror if the idx_original_string value is lower than 0 or greater than len bwt_string 1 reverse_bwt bnn aaa 6 banana reverse_bwt aaaadss_c__aa 3 a_asa_da_casa reverse_bwt mnpbnnaaaaaa 11 panamabanana reverse_bwt 4 11 traceback most recent call last typeerror the parameter bwt_string type must be str reverse_bwt 11 traceback most recent call last valueerror the parameter bwt_string must not be empty reverse_bwt mnpbnnaaaaaa asd doctest normalize_whitespace traceback most recent call last typeerror the parameter idx_original_string type must be int or passive of cast to int reverse_bwt mnpbnnaaaaaa 1 traceback most recent call last valueerror the parameter idx_original_string must not be lower than 0 reverse_bwt mnpbnnaaaaaa 12 doctest normalize_whitespace traceback most recent call last valueerror the parameter idx_original_string must be lower than len bwt_string reverse_bwt mnpbnnaaaaaa 11 0 panamabanana reverse_bwt mnpbnnaaaaaa 11 4 panamabanana
from __future__ import annotations from typing import TypedDict class BWTTransformDict(TypedDict): bwt_string: str idx_original_string: int def all_rotations(s: str) -> list[str]: if not isinstance(s, str): raise TypeError("The parameter s type must be str.") return [s[i:] + s[:i] for i in range(len(s))] def bwt_transform(s: str) -> BWTTransformDict: if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() response: BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } return response def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for _ in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": entry_msg = "Provide a string that I will generate its BWT transform: " s = input(entry_msg).strip() result = bwt_transform(s) print( f"Burrows Wheeler transform for string '{s}' results " f"in '{result['bwt_string']}'" ) original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " f"we get original string '{original_string}'" )
read the file and build a dict of all letters and their frequencies then convert the dict into a list of letters run through the list of letters and build the min heap for the huffman tree recursively traverse the huffman tree to set each letter s bitstring dictionary and return the list of letters parse the file build the tree then run through the file again using the letters dictionary to find and print out the bitstring for each letter pass the file path to the huffman function read the file and build a dict of all letters and their frequencies then convert the dict into a list of letters run through the list of letters and build the min heap for the huffman tree type ignore recursively traverse the huffman tree to set each letter s bitstring dictionary and return the list of letters type ignore parse the file build the tree then run through the file again using the letters dictionary to find and print out the bitstring for each letter pass the file path to the huffman function
from __future__ import annotations import sys class Letter: def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {} def __repr__(self) -> str: return f"{self.letter}:{self.freq}" class TreeNode: def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda x: x.freq) def build_tree(letters: list[Letter]) -> Letter | TreeNode: response: list[Letter | TreeNode] = letters while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda x: x.freq) return response[0] def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: if isinstance(root, Letter): root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters def huffman(file_path: str) -> None: letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print() if __name__ == "__main__": huffman(sys.argv[1])
one of the several implementations of lempelzivwelch compression algorithm https en wikipedia orgwikilempele28093zive28093welch reads given file as bytes and returns them as a long string adds new strings currstring 0 currstring 1 to the lexicon compresses given databits using lempelzivwelch compression algorithm and returns the result as a string adds given file s length in front using elias gamma coding of the compressed string writes given towrite string should only consist of 0 s and 1 s as bytes in the file reads source file compresses it and writes the compressed result in destination file reads given file as bytes and returns them as a long string adds new strings curr_string 0 curr_string 1 to the lexicon compresses given data_bits using lempel ziv welch compression algorithm and returns the result as a string adds given file s length in front using elias gamma coding of the compressed string writes given to_write string should only consist of 0 s and 1 s as bytes in the file reads source file compresses it and writes the compressed result in destination file
import math import os import sys def read_file_binary(file_path: str) -> str: result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def add_key_to_lexicon( lexicon: dict[str, str], curr_string: str, index: int, last_match_id: str ) -> None: lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key in lexicon: lexicon[curr_key] = "0" + lexicon[curr_key] lexicon[curr_string + "1"] = bin(index)[2:] def compress_data(data_bits: str) -> str: lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result def add_file_length(source_path: str, compressed: str) -> str: file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed def write_file_binary(file_path: str, to_write: str) -> None: byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def compress(source_path: str, destination_path: str) -> None: data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
one of the several implementations of lempelzivwelch decompression algorithm https en wikipedia orgwikilempele28093zive28093welch reads given file as bytes and returns them as a long string decompresses given databits using lempelzivwelch compression algorithm and returns the result as a string writes given towrite string should only consist of 0 s and 1 s as bytes in the file removes size prefix that compressed file should have returns the result reads source file decompresses it and writes the result in destination file reads given file as bytes and returns them as a long string decompresses given data_bits using lempel ziv welch compression algorithm and returns the result as a string writes given to_write string should only consist of 0 s and 1 s as bytes in the file removes size prefix that compressed file should have returns the result reads source file decompresses it and writes the result in destination file
import math import sys def read_file_binary(file_path: str) -> str: result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def decompress_data(data_bits: str) -> str: lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id lexicon[curr_string] = last_match_id + "0" if math.log2(index).is_integer(): new_lex = {} for curr_key in list(lexicon): new_lex["0" + curr_key] = lexicon.pop(curr_key) lexicon = new_lex lexicon[bin(index)[2:]] = last_match_id + "1" index += 1 curr_string = "" return result def write_file_binary(file_path: str, to_write: str) -> None: byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def remove_prefix(data_bits: str) -> str: counter = 0 for letter in data_bits: if letter == "1": break counter += 1 data_bits = data_bits[counter:] data_bits = data_bits[counter + 1 :] return data_bits def compress(source_path: str, destination_path: str) -> None: data_bits = read_file_binary(source_path) data_bits = remove_prefix(data_bits) decompressed = decompress_data(data_bits) write_file_binary(destination_path, decompressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
lz77 compression algorithm lossless data compression published in papers by abraham lempel and jacob ziv in 1977 also known as lz1 or slidingwindow compression form the basis for many variations including lzw lzss lzma and others it uses a sliding window method within the sliding window we have search buffer look ahead buffer lenslidingwindow lensearchbuffer lenlookaheadbuffer lz77 manages a dictionary that uses triples composed of offset into search buffer it s the distance between the start of a phrase and the beginning of a file length of the match it s the number of characters that make up a phrase the indicator is represented by a character that is going to be encoded next as a file is parsed the dictionary is dynamically updated to reflect the compressed data contents and size examples cabracadabrarrarrad 0 0 c 0 0 a 0 0 b 0 0 r 3 1 c 2 1 d 7 4 r 3 5 d ababcbababaa 0 0 a 0 0 b 2 2 c 4 3 a 2 2 a aacaacabcabaaac 0 0 a 1 1 c 3 4 b 3 3 a 1 2 c sources en wikipedia orgwikilz77andlz78 dataclass representing triplet called token consisting of length offset and indicator this triplet is used during lz77 compression token token1 2 c reprtoken 1 2 c strtoken 1 2 c class containing compress and decompress methods using lz77 compression algorithm compress the given string text using lz77 compression algorithm args text string to be compressed returns output the compressed text as a list of tokens lz77compressor lz77compressor strlz77compressor compressababcbababaa 0 0 a 0 0 b 2 2 c 4 3 a 2 2 a strlz77compressor compressaacaacabcabaaac 0 0 a 1 1 c 3 4 b 3 3 a 1 2 c while there are still characters in text to compress find the next encoding phrase triplet with offset length indicator the next encoding character update the search buffer add new characters from text into it check if size exceed the max search buffer size if so drop the oldest elements update the text append the token to output convert the list of tokens into an output string args tokens list containing triplets offset length char returns output decompressed text tests lz77compressor lz77compressor lz77compressor decompresstoken0 0 c token0 0 a token0 0 b token0 0 r token3 1 c token2 1 d token7 4 r token3 5 d cabracadabrarrarrad lz77compressor decompresstoken0 0 a token0 0 b token2 2 c token4 3 a token2 2 a ababcbababaa lz77compressor decompresstoken0 0 a token1 1 c token3 4 b token3 3 a token1 2 c aacaacabcabaaac finds the encoding token for the first character in the text tests lz77compressor lz77compressor lz77compressor findencodingtokenabrarrarrad abracad offset 7 lz77compressor findencodingtokenadabrarrarrad cabrac length 1 lz77compressor findencodingtokenabc xyz offset 0 lz77compressor findencodingtoken xyz offset traceback most recent call last valueerror we need some text to work with lz77compressor findencodingtokenabc offset 0 initialise result parameters to default values if the found length is bigger than the current or if it s equal which means it s offset is smaller update offset and length calculate the longest possible match of text and window characters from textindex in text and windowindex in window args text description window sliding window textindex index of character in text windowindex index of character in sliding window returns the maximum match between text and window from given indexes tests lz77compressor lz77compressor13 6 lz77compressor matchlengthfromindexrarrad adabrar 0 4 5 lz77compressor matchlengthfromindexadabrarrarrad cabrac 0 1 1 initialize compressor class example dataclass representing triplet called token consisting of length offset and indicator this triplet is used during lz77 compression token token 1 2 c repr token 1 2 c str token 1 2 c class containing compress and decompress methods using lz77 compression algorithm compress the given string text using lz77 compression algorithm args text string to be compressed returns output the compressed text as a list of tokens lz77_compressor lz77compressor str lz77_compressor compress ababcbababaa 0 0 a 0 0 b 2 2 c 4 3 a 2 2 a str lz77_compressor compress aacaacabcabaaac 0 0 a 1 1 c 3 4 b 3 3 a 1 2 c while there are still characters in text to compress find the next encoding phrase triplet with offset length indicator the next encoding character update the search buffer add new characters from text into it check if size exceed the max search buffer size if so drop the oldest elements update the text append the token to output convert the list of tokens into an output string args tokens list containing triplets offset length char returns output decompressed text tests lz77_compressor lz77compressor lz77_compressor decompress token 0 0 c token 0 0 a token 0 0 b token 0 0 r token 3 1 c token 2 1 d token 7 4 r token 3 5 d cabracadabrarrarrad lz77_compressor decompress token 0 0 a token 0 0 b token 2 2 c token 4 3 a token 2 2 a ababcbababaa lz77_compressor decompress token 0 0 a token 1 1 c token 3 4 b token 3 3 a token 1 2 c aacaacabcabaaac finds the encoding token for the first character in the text tests lz77_compressor lz77compressor lz77_compressor _find_encoding_token abrarrarrad abracad offset 7 lz77_compressor _find_encoding_token adabrarrarrad cabrac length 1 lz77_compressor _find_encoding_token abc xyz offset 0 lz77_compressor _find_encoding_token xyz offset traceback most recent call last valueerror we need some text to work with lz77_compressor _find_encoding_token abc offset 0 initialise result parameters to default values if the found length is bigger than the current or if it s equal which means it s offset is smaller update offset and length calculate the longest possible match of text and window characters from text_index in text and window_index in window args text _description_ window sliding window text_index index of character in text window_index index of character in sliding window returns the maximum match between text and window from given indexes tests lz77_compressor lz77compressor 13 6 lz77_compressor _match_length_from_index rarrad adabrar 0 4 5 lz77_compressor _match_length_from_index adabrarrarrad cabrac 0 1 1 initialize compressor class example
from dataclasses import dataclass __version__ = "0.1" __author__ = "Lucia Harcekova" @dataclass class Token: offset: int length: int indicator: str def __repr__(self) -> str: return f"({self.offset}, {self.length}, {self.indicator})" class LZ77Compressor: def __init__(self, window_size: int = 13, lookahead_buffer_size: int = 6) -> None: self.window_size = window_size self.lookahead_buffer_size = lookahead_buffer_size self.search_buffer_size = self.window_size - self.lookahead_buffer_size def compress(self, text: str) -> list[Token]: output = [] search_buffer = "" while text: token = self._find_encoding_token(text, search_buffer) search_buffer += text[: token.length + 1] if len(search_buffer) > self.search_buffer_size: search_buffer = search_buffer[-self.search_buffer_size :] text = text[token.length + 1 :] output.append(token) return output def decompress(self, tokens: list[Token]) -> str: output = "" for token in tokens: for _ in range(token.length): output += output[-token.offset] output += token.indicator return output def _find_encoding_token(self, text: str, search_buffer: str) -> Token: if not text: raise ValueError("We need some text to work with.") length, offset = 0, 0 if not search_buffer: return Token(offset, length, text[length]) for i, character in enumerate(search_buffer): found_offset = len(search_buffer) - i if character == text[0]: found_length = self._match_length_from_index(text, search_buffer, 0, i) if found_length >= length: offset, length = found_offset, found_length return Token(offset, length, text[length]) def _match_length_from_index( self, text: str, window: str, text_index: int, window_index: int ) -> int: if not text or text[text_index] != window[window_index]: return 0 return 1 + self._match_length_from_index( text, window + text[text_index], text_index + 1, window_index + 1 ) if __name__ == "__main__": from doctest import testmod testmod() lz77_compressor = LZ77Compressor(window_size=13, lookahead_buffer_size=6) TEXT = "cabracadabrarrarrad" compressed_text = lz77_compressor.compress(TEXT) print(lz77_compressor.compress("ababcbababaa")) decompressed_text = lz77_compressor.decompress(compressed_text) assert decompressed_text == TEXT, "The LZ77 algorithm returned the invalid result."
peak signaltonoise ratio psnr https en wikipedia orgwikipeaksignaltonoiseratio source https tutorials techonical comhowtocalculatepsnrvalueoftwoimagesusingpython loading images original image and compressed image value expected 29 73db value expected 31 53db wikipedia example loading images original image and compressed image value expected 29 73db value expected 31 53db wikipedia example
import math import os import cv2 import numpy as np PIXEL_MAX = 255.0 def peak_signal_to_noise_ratio(original: float, contrast: float) -> float: mse = np.mean((original - contrast) ** 2) if mse == 0: return 100 return 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) def main() -> None: dir_path = os.path.dirname(os.path.realpath(__file__)) original = cv2.imread(os.path.join(dir_path, "image_data/original_image.png")) contrast = cv2.imread(os.path.join(dir_path, "image_data/compressed_image.png"), 1) original2 = cv2.imread(os.path.join(dir_path, "image_data/PSNR-example-base.png")) contrast2 = cv2.imread( os.path.join(dir_path, "image_data/PSNR-example-comp-10.jpg"), 1 ) print("-- First Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original, contrast)} dB") print("\n-- Second Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original2, contrast2)} dB") if __name__ == "__main__": main()
https en wikipedia orgwikirunlengthencoding performs run length encoding runlengthencodeaaaabbbccdaa a 4 b 3 c 2 d 1 a 2 runlengthencodea a 1 runlengthencodeaa a 2 runlengthencodeaaaddddddfffcccaavvvv a 3 d 6 f 3 c 3 a 2 v 4 performs run length decoding runlengthdecode a 4 b 3 c 2 d 1 a 2 aaaabbbccdaa runlengthdecode a 1 a runlengthdecode a 2 aa runlengthdecode a 3 d 6 f 3 c 3 a 2 v 4 aaaddddddfffcccaavvvv https en wikipedia org wiki run length_encoding performs run length encoding run_length_encode aaaabbbccdaa a 4 b 3 c 2 d 1 a 2 run_length_encode a a 1 run_length_encode aa a 2 run_length_encode aaaddddddfffcccaavvvv a 3 d 6 f 3 c 3 a 2 v 4 performs run length decoding run_length_decode a 4 b 3 c 2 d 1 a 2 aaaabbbccdaa run_length_decode a 1 a run_length_decode a 2 aa run_length_decode a 3 d 6 f 3 c 3 a 2 v 4 aaaddddddfffcccaavvvv
def run_length_encode(text: str) -> list: encoded = [] count = 1 for i in range(len(text)): if i + 1 < len(text) and text[i] == text[i + 1]: count += 1 else: encoded.append((text[i], count)) count = 1 return encoded def run_length_decode(encoded: list) -> str: return "".join(char * length for char, length in encoded) if __name__ == "__main__": from doctest import testmod testmod(name="run_length_encode", verbose=True) testmod(name="run_length_decode", verbose=True)
flip image and bounding box for computer vision task https paperswithcode commethodrandomhorizontalflip params get images list and annotations list from input dir update new images and annotations save images and annotations in output dir get random string code 7b7ad245cdff75241935e4dd860f3bad labeldir type str path to label include annotation of images imgdir type str path to folder contain images return type list list of images path and labels imglist type list list of all images annolist type list list of all annotations of specific image fliptype type int 0 is vertical 1 is horizontal return newimgslist type narray image after resize newannoslists type list list of new annotation after scale pathlist type list list the name of image file automatic generate random 32 characters get random string code 7b7ad245cdff75241935e4dd860f3bad lenrandomchars32 32 flip image and bounding box for computer vision task https paperswithcode com method randomhorizontalflip params 0 is vertical 1 is horizontal get images list and annotations list from input dir update new images and annotations save images and annotations in output dir get random string code 7b7ad245cdff75241935e4dd860f3bad label_dir type str path to label include annotation of images img_dir type str path to folder contain images return type list list of images path and labels img_list type list list of all images anno_list type list list of all annotations of specific image flip_type type int 0 is vertical 1 is horizontal return new_imgs_list type narray image after resize new_annos_lists type list list of new annotation after scale path_list type list list the name of image file automatic generate random 32 characters get random string code 7b7ad245cdff75241935e4dd860f3bad len random_chars 32 32
import glob import os import random from string import ascii_lowercase, digits import cv2 LABEL_DIR = "" IMAGE_DIR = "" OUTPUT_DIR = "" FLIP_TYPE = 1 def main() -> None: img_paths, annos = get_dataset(LABEL_DIR, IMAGE_DIR) print("Processing...") new_images, new_annos, paths = update_image_and_anno(img_paths, annos, FLIP_TYPE) for index, image in enumerate(new_images): letter_code = random_chars(32) file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}" cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Success {index+1}/{len(new_images)} with {file_name}") annos_list = [] for anno in new_annos[index]: obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}" annos_list.append(obj) with open(f"{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") boxes.append( [ int(obj[0]), float(obj[1]), float(obj[2]), float(obj[3]), float(obj[4]), ] ) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( img_list: list, anno_list: list, flip_type: int = 1 ) -> tuple[list, list, list]: new_annos_lists = [] path_list = [] new_imgs_list = [] for idx in range(len(img_list)): new_annos = [] path = img_list[idx] path_list.append(path) img_annos = anno_list[idx] img = cv2.imread(path) if flip_type == 1: new_img = cv2.flip(img, flip_type) for bbox in img_annos: x_center_new = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]]) elif flip_type == 0: new_img = cv2.flip(img, flip_type) for bbox in img_annos: y_center_new = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]]) new_annos_lists.append(new_annos) new_imgs_list.append(new_img) return new_imgs_list, new_annos_lists, path_list def random_chars(number_char: int = 32) -> str: assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
https en wikipedia orgwikiimagetexture https en wikipedia orgwikicooccurrencematrixapplicationtoimageanalysis simple implementation of root mean squared error for two n dimensional numpy arrays examples rootmeansquareerrornp array1 2 3 np array1 2 3 0 0 rootmeansquareerrornp array1 2 3 np array2 2 2 0 816496580927726 rootmeansquareerrornp array1 2 3 np array6 4 2 3 1622776601683795 normalizes image in numpy 2d array format between ranges 0cap as to fit uint8 type args image 2d numpy array representing image as matrix with values in any range cap maximum cap amount for normalization datatype numpy data type to set output variable to returns return 2d numpy array of type uint8 corresponding to limited range matrix examples normalizeimagenp array1 2 3 4 5 10 cap1 0 datatypenp float64 array0 0 11111111 0 22222222 0 33333333 0 44444444 1 normalizeimagenp array4 4 3 1 7 2 array127 127 85 0 255 42 dtypeuint8 normalizes a 1d array between ranges 0cap args array list containing values to be normalized between cap range cap maximum cap amount for normalization returns return 1d numpy array corresponding to limited range array examples normalizearraynp array2 3 5 7 array0 0 2 0 6 1 normalizearraynp array5 7 11 13 array0 0 25 0 75 1 uses luminance weights to transform rgb channel to greyscale by taking the dot product between the channel and the weights example grayscalenp array108 201 72 255 11 127 56 56 56 128 255 107 array158 97 56 200 dtypeuint8 binarizes a grayscale image based on a given threshold value setting values to 1 or 0 accordingly examples binarizenp array128 255 101 156 array1 1 0 1 binarizenp array0 07 1 0 51 0 3 threshold0 5 array0 1 1 0 simple image transformation using one of two available filter functions erosion and dilation args image binarized input image onto which to apply transformation kind can be either erosion in which case the func np max function is called or dilation when func np min is used instead kernel n x n kernel with shape attr image shape to be used when applying convolution to original image returns returns a numpy array with same shape as input image corresponding to applied binary transformation examples img np array1 0 5 0 2 0 7 img binarizeimg threshold0 5 transformimg erosion array1 1 1 1 dtypeuint8 transformimg dilation array0 0 0 0 dtypeuint8 use padded image when applying convolotion to not go out of bounds of the original the image apply transformation method to the centered section of the image opening filter defined as the sequence of erosion and then a dilation filter on the same image examples img np array1 0 5 0 2 0 7 img binarizeimg threshold0 5 openingfilterimg array1 1 1 1 dtypeuint8 opening filter defined as the sequence of dilation and then erosion filter on the same image examples img np array1 0 5 0 2 0 7 img binarizeimg threshold0 5 closingfilterimg array0 0 0 0 dtypeuint8 apply binary mask or thresholding based on bit mask value mapping mask is binary returns the mapped true value mask and its complementary false value mask example img np array108 201 72 255 11 127 56 56 56 128 255 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary binarymaskgray morphological array1 1 1 1 dtypeuint8 array158 97 56 200 dtypeuint8 calculate sample cooccurrence matrix based on input image as well as selected coordinates on image implementation is made using basic iteration as function to be performed np max is nonlinear and therefore not callable on the frequency domain example img np array108 201 72 255 11 127 56 56 56 128 255 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary mask1 binarymaskgray morphological0 matrixconcurrencymask1 0 1 array0 0 0 0 calculates all 8 haralick descriptors based on cooccurrence input matrix all descriptors are as follows maximum probability inverse difference homogeneity entropy energy dissimilarity contrast and correlation args matrix cooccurrence matrix to use as base for calculating descriptors returns reverse ordered list of resulting descriptors example img np array108 201 72 255 11 127 56 56 56 128 255 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary mask1 binarymaskgray morphological0 concurrency matrixconcurrencymask1 0 1 haralickdescriptorsconcurrency 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 function np indices could be used for bigger input types but np ogrid works just fine precalculate frequent multiplication and subtraction calculate numerical value of maximum probability using the definition for each descriptor individually to calculate its matrix sum values for descriptors ranging from the first one to the last as all are their respective origin matrix and not the resulting value yet calculate all haralick descriptors for a sequence of different cooccurrence matrices given input masks and coordinates example img np array108 201 72 255 11 127 56 56 56 128 255 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary getdescriptorsbinarymaskgray morphological 0 1 array0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 concatenate each individual descriptor into one single list containing sequence of descriptors simple method for calculating the euclidean distance between two points with type np ndarray example a np array1 0 2 b np array2 1 1 euclideana b 3 3166247903554 calculate all euclidean distances between a selected base descriptor and all other haralick descriptors the resulting comparison is return in decreasing order showing which descriptor is the most similar to the selected base args descriptors haralick descriptors to compare with base index base haralick descriptor index to use as base when calculating respective euclidean distance to other descriptors returns ordered distances between descriptors example index 1 img np array108 201 72 255 11 127 56 56 56 128 255 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary getdistancesgetdescriptors binarymaskgray morphological 0 1 index 0 0 0 1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0 7 0 0 8 0 0 9 0 0 10 0 0 11 0 0 12 0 0 13 0 0 14 0 0 15 0 0 normalize distances between range 0 1 index to compare haralick descriptors to format is the respective filter to apply can be either 1 for the opening filter or else for the closing number of images to perform methods on open given image and calculate morphological filter respective masks and correspondent harralick descriptors transform ordered distances array into a sequence of indexes corresponding to original file position finally print distances considering the haralick descriptions from the base file to all other images using the morphology method of choice simple implementation of root mean squared error for two n dimensional numpy arrays examples root_mean_square_error np array 1 2 3 np array 1 2 3 0 0 root_mean_square_error np array 1 2 3 np array 2 2 2 0 816496580927726 root_mean_square_error np array 1 2 3 np array 6 4 2 3 1622776601683795 normalizes image in numpy 2d array format between ranges 0 cap as to fit uint8 type args image 2d numpy array representing image as matrix with values in any range cap maximum cap amount for normalization data_type numpy data type to set output variable to returns return 2d numpy array of type uint8 corresponding to limited range matrix examples normalize_image np array 1 2 3 4 5 10 cap 1 0 data_type np float64 array 0 0 11111111 0 22222222 0 33333333 0 44444444 1 normalize_image np array 4 4 3 1 7 2 array 127 127 85 0 255 42 dtype uint8 normalizes a 1d array between ranges 0 cap args array list containing values to be normalized between cap range cap maximum cap amount for normalization returns return 1d numpy array corresponding to limited range array examples normalize_array np array 2 3 5 7 array 0 0 2 0 6 1 normalize_array np array 5 7 11 13 array 0 0 25 0 75 1 uses luminance weights to transform rgb channel to greyscale by taking the dot product between the channel and the weights example grayscale np array 108 201 72 255 11 127 56 56 56 128 255 107 array 158 97 56 200 dtype uint8 binarizes a grayscale image based on a given threshold value setting values to 1 or 0 accordingly examples binarize np array 128 255 101 156 array 1 1 0 1 binarize np array 0 07 1 0 51 0 3 threshold 0 5 array 0 1 1 0 simple image transformation using one of two available filter functions erosion and dilation args image binarized input image onto which to apply transformation kind can be either erosion in which case the func np max function is called or dilation when func np min is used instead kernel n x n kernel with shape attr image shape to be used when applying convolution to original image returns returns a numpy array with same shape as input image corresponding to applied binary transformation examples img np array 1 0 5 0 2 0 7 img binarize img threshold 0 5 transform img erosion array 1 1 1 1 dtype uint8 transform img dilation array 0 0 0 0 dtype uint8 use padded image when applying convolotion to not go out of bounds of the original the image apply transformation method to the centered section of the image opening filter defined as the sequence of erosion and then a dilation filter on the same image examples img np array 1 0 5 0 2 0 7 img binarize img threshold 0 5 opening_filter img array 1 1 1 1 dtype uint8 opening filter defined as the sequence of dilation and then erosion filter on the same image examples img np array 1 0 5 0 2 0 7 img binarize img threshold 0 5 closing_filter img array 0 0 0 0 dtype uint8 apply binary mask or thresholding based on bit mask value mapping mask is binary returns the mapped true value mask and its complementary false value mask example img np array 108 201 72 255 11 127 56 56 56 128 255 107 gray grayscale img binary binarize gray morphological opening_filter binary binary_mask gray morphological array 1 1 1 1 dtype uint8 array 158 97 56 200 dtype uint8 calculate sample co occurrence matrix based on input image as well as selected coordinates on image implementation is made using basic iteration as function to be performed np max is non linear and therefore not callable on the frequency domain example img np array 108 201 72 255 11 127 56 56 56 128 255 107 gray grayscale img binary binarize gray morphological opening_filter binary mask_1 binary_mask gray morphological 0 matrix_concurrency mask_1 0 1 array 0 0 0 0 calculates all 8 haralick descriptors based on co occurrence input matrix all descriptors are as follows maximum probability inverse difference homogeneity entropy energy dissimilarity contrast and correlation args matrix co occurrence matrix to use as base for calculating descriptors returns reverse ordered list of resulting descriptors example img np array 108 201 72 255 11 127 56 56 56 128 255 107 gray grayscale img binary binarize gray morphological opening_filter binary mask_1 binary_mask gray morphological 0 concurrency matrix_concurrency mask_1 0 1 haralick_descriptors concurrency 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 function np indices could be used for bigger input types but np ogrid works just fine np indices pre calculate frequent multiplication and subtraction calculate numerical value of maximum probability using the definition for each descriptor individually to calculate its matrix sum values for descriptors ranging from the first one to the last as all are their respective origin matrix and not the resulting value yet calculate all haralick descriptors for a sequence of different co occurrence matrices given input masks and coordinates example img np array 108 201 72 255 11 127 56 56 56 128 255 107 gray grayscale img binary binarize gray morphological opening_filter binary get_descriptors binary_mask gray morphological 0 1 array 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 concatenate each individual descriptor into one single list containing sequence of descriptors simple method for calculating the euclidean distance between two points with type np ndarray example a np array 1 0 2 b np array 2 1 1 euclidean a b 3 3166247903554 calculate all euclidean distances between a selected base descriptor and all other haralick descriptors the resulting comparison is return in decreasing order showing which descriptor is the most similar to the selected base args descriptors haralick descriptors to compare with base index base haralick descriptor index to use as base when calculating respective euclidean distance to other descriptors returns ordered distances between descriptors example index 1 img np array 108 201 72 255 11 127 56 56 56 128 255 107 gray grayscale img binary binarize gray morphological opening_filter binary get_distances get_descriptors binary_mask gray morphological 0 1 index 0 0 0 1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0 7 0 0 8 0 0 9 0 0 10 0 0 11 0 0 12 0 0 13 0 0 14 0 0 15 0 0 normalize distances between range 0 1 index to compare haralick descriptors to format is the respective filter to apply can be either 1 for the opening filter or else for the closing number of images to perform methods on open given image and calculate morphological filter respective masks and correspondent harralick descriptors transform ordered distances array into a sequence of indexes corresponding to original file position finally print distances considering the haralick descriptions from the base file to all other images using the morphology method of choice
import imageio.v2 as imageio import numpy as np def root_mean_square_error(original: np.ndarray, reference: np.ndarray) -> float: return np.sqrt(((original - reference) ** 2).mean()) def normalize_image( image: np.ndarray, cap: float = 255.0, data_type: np.dtype = np.uint8 ) -> np.ndarray: normalized = (image - np.min(image)) / (np.max(image) - np.min(image)) * cap return normalized.astype(data_type) def normalize_array(array: np.ndarray, cap: float = 1) -> np.ndarray: diff = np.max(array) - np.min(array) return (array - np.min(array)) / (1 if diff == 0 else diff) * cap def grayscale(image: np.ndarray) -> np.ndarray: return np.dot(image[:, :, 0:3], [0.299, 0.587, 0.114]).astype(np.uint8) def binarize(image: np.ndarray, threshold: float = 127.0) -> np.ndarray: return np.where(image > threshold, 1, 0) def transform( image: np.ndarray, kind: str, kernel: np.ndarray | None = None ) -> np.ndarray: if kernel is None: kernel = np.ones((3, 3)) if kind == "erosion": constant = 1 apply = np.max else: constant = 0 apply = np.min center_x, center_y = (x // 2 for x in kernel.shape) transformed = np.zeros(image.shape, dtype=np.uint8) padded = np.pad(image, 1, "constant", constant_values=constant) for x in range(center_x, padded.shape[0] - center_x): for y in range(center_y, padded.shape[1] - center_y): center = padded[ x - center_x : x + center_x + 1, y - center_y : y + center_y + 1 ] transformed[x - center_x, y - center_y] = apply(center[kernel == 1]) return transformed def opening_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray: if kernel is None: np.ones((3, 3)) return transform(transform(image, "dilation", kernel), "erosion", kernel) def closing_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray: if kernel is None: kernel = np.ones((3, 3)) return transform(transform(image, "erosion", kernel), "dilation", kernel) def binary_mask( image_gray: np.ndarray, image_map: np.ndarray ) -> tuple[np.ndarray, np.ndarray]: true_mask, false_mask = image_gray.copy(), image_gray.copy() true_mask[image_map == 1] = 1 false_mask[image_map == 0] = 0 return true_mask, false_mask def matrix_concurrency(image: np.ndarray, coordinate: tuple[int, int]) -> np.ndarray: matrix = np.zeros([np.max(image) + 1, np.max(image) + 1]) offset_x, offset_y = coordinate for x in range(1, image.shape[0] - 1): for y in range(1, image.shape[1] - 1): base_pixel = image[x, y] offset_pixel = image[x + offset_x, y + offset_y] matrix[base_pixel, offset_pixel] += 1 matrix_sum = np.sum(matrix) return matrix / (1 if matrix_sum == 0 else matrix_sum) def haralick_descriptors(matrix: np.ndarray) -> list[float]: i, j = np.ogrid[0 : matrix.shape[0], 0 : matrix.shape[1]] prod = np.multiply(i, j) sub = np.subtract(i, j) maximum_prob = np.max(matrix) correlation = prod * matrix energy = np.power(matrix, 2) contrast = matrix * np.power(sub, 2) dissimilarity = matrix * np.abs(sub) inverse_difference = matrix / (1 + np.abs(sub)) homogeneity = matrix / (1 + np.power(sub, 2)) entropy = -(matrix[matrix > 0] * np.log(matrix[matrix > 0])) return [ maximum_prob, correlation.sum(), energy.sum(), contrast.sum(), dissimilarity.sum(), inverse_difference.sum(), homogeneity.sum(), entropy.sum(), ] def get_descriptors( masks: tuple[np.ndarray, np.ndarray], coordinate: tuple[int, int] ) -> np.ndarray: descriptors = np.array( [haralick_descriptors(matrix_concurrency(mask, coordinate)) for mask in masks] ) return np.concatenate(descriptors, axis=None) def euclidean(point_1: np.ndarray, point_2: np.ndarray) -> np.float32: return np.sqrt(np.sum(np.square(point_1 - point_2))) def get_distances(descriptors: np.ndarray, base: int) -> list[tuple[int, float]]: distances = np.array( [euclidean(descriptor, descriptors[base]) for descriptor in descriptors] ) normalized_distances: list[float] = normalize_array(distances, 1).tolist() enum_distances = list(enumerate(normalized_distances)) enum_distances.sort(key=lambda tup: tup[1], reverse=True) return enum_distances if __name__ == "__main__": index = int(input()) q_value_list = [int(value) for value in input().split()] q_value = (q_value_list[0], q_value_list[1]) parameters = {"format": int(input()), "threshold": int(input())} b_number = int(input()) files, descriptors = [], [] for _ in range(b_number): file = input().rstrip() files.append(file) image = imageio.imread(file).astype(np.float32) gray = grayscale(image) threshold = binarize(gray, parameters["threshold"]) morphological = ( opening_filter(threshold) if parameters["format"] == 1 else closing_filter(threshold) ) masks = binary_mask(gray, morphological) descriptors.append(get_descriptors(masks, q_value)) distances = get_distances(np.array(descriptors), index) indexed_distances = np.array(distances).astype(np.uint8)[:, 0] print(f"Query: {files[index]}") print("Ranking:") for idx, file_idx in enumerate(indexed_distances): print(f"({idx}) {files[file_idx]}", end="\n")
harris corner detector https en wikipedia orgwikiharriscornerdetector k is an empirically determined constant in 0 04 0 06 windowsize neighbourhoods considered returns the image with corners identified imgpath path of the image output list of the corner positions image can change the value harris corner detector https en wikipedia org wiki harris_corner_detector k is an empirically determined constant in 0 04 0 06 window_size neighbourhoods considered returns the image with corners identified img_path path of the image output list of the corner positions image can change the value
import cv2 import numpy as np class HarrisCorner: def __init__(self, k: float, window_size: int): if k in (0.04, 0.06): self.k = k self.window_size = window_size else: raise ValueError("invalid k value") def __str__(self) -> str: return str(self.k) def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: img = cv2.imread(img_path, 0) h, w = img.shape corner_list: list[list[int]] = [] color_img = img.copy() color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) dy, dx = np.gradient(img) ixx = dx**2 iyy = dy**2 ixy = dx * dy k = 0.04 offset = self.window_size // 2 for y in range(offset, h - offset): for x in range(offset, w - offset): wxx = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wyy = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wxy = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() det = (wxx * wyy) - (wxy**2) trace = wxx + wyy r = det - k * (trace**2) if r > 0.5: corner_list.append([x, y, r]) color_img.itemset((y, x, 0), 0) color_img.itemset((y, x, 1), 0) color_img.itemset((y, x, 2), 255) return color_img, corner_list if __name__ == "__main__": edge_detect = HarrisCorner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") cv2.imwrite("detect.png", color_img)
the hornschunck method estimates the optical flow for every single pixel of a sequence of images it works by assuming brightness constancy between two consecutive frames and smoothness in the optical flow useful resources wikipedia https en wikipedia orgwikihorne28093schunckmethod paper http image diku dkimagecanonmaterialhornschunckopticalflow pdf warps the pixels of an image into a new image using the horizontal and vertical flows pixels that are warped from an invalid location are set to 0 parameters image grayscale image horizontalflow horizontal flow verticalflow vertical flow returns warped image warpnp array0 1 2 0 3 0 2 2 2 np array0 1 1 1 0 0 1 1 1 np array0 0 0 0 1 0 0 0 1 array0 0 0 3 1 0 0 2 3 create a grid of all pixel coordinates and subtract the flow to get the target pixels coordinates find the locations outside of the original image set pixels at invalid locations to 0 this function performs the hornschunck algorithm and returns the estimated optical flow it is assumed that the input images are grayscale and normalized to be in 0 1 parameters image0 first image of the sequence image1 second image of the sequence alpha regularization constant numiter number of iterations performed returns estimated horizontal vertical flow np roundhornschuncknp array0 0 2 0 0 2 np array0 2 0 0 2 0 alpha0 1 numiter110 astypenp int32 array 0 1 1 0 1 1 blankline 0 0 0 0 0 0 dtypeint32 initialize flow prepare kernels for the calculation of the derivatives and the average velocity iteratively refine the flow this updates the flow as proposed in the paper step 12 warps the pixels of an image into a new image using the horizontal and vertical flows pixels that are warped from an invalid location are set to 0 parameters image grayscale image horizontal_flow horizontal flow vertical_flow vertical flow returns warped image warp np array 0 1 2 0 3 0 2 2 2 np array 0 1 1 1 0 0 1 1 1 np array 0 0 0 0 1 0 0 0 1 array 0 0 0 3 1 0 0 2 3 create a grid of all pixel coordinates and subtract the flow to get the target pixels coordinates find the locations outside of the original image set pixels at invalid locations to 0 this function performs the horn schunck algorithm and returns the estimated optical flow it is assumed that the input images are grayscale and normalized to be in 0 1 parameters image0 first image of the sequence image1 second image of the sequence alpha regularization constant num_iter number of iterations performed returns estimated horizontal vertical flow np round horn_schunck np array 0 0 2 0 0 2 np array 0 2 0 0 2 0 alpha 0 1 num_iter 110 astype np int32 array 0 1 1 0 1 1 blankline 0 0 0 0 0 0 dtype int32 initialize flow prepare kernels for the calculation of the derivatives and the average velocity iteratively refine the flow this updates the flow as proposed in the paper step 12
from typing import SupportsIndex import numpy as np from scipy.ndimage import convolve def warp( image: np.ndarray, horizontal_flow: np.ndarray, vertical_flow: np.ndarray ) -> np.ndarray: flow = np.stack((horizontal_flow, vertical_flow), 2) grid = np.stack( np.meshgrid(np.arange(0, image.shape[1]), np.arange(0, image.shape[0])), 2 ) grid = np.round(grid - flow).astype(np.int32) invalid = (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]])) grid[invalid] = 0 warped = image[grid[:, :, 1], grid[:, :, 0]] warped[invalid[:, :, 0] | invalid[:, :, 1]] = 0 return warped def horn_schunck( image0: np.ndarray, image1: np.ndarray, num_iter: SupportsIndex, alpha: float | None = None, ) -> tuple[np.ndarray, np.ndarray]: if alpha is None: alpha = 0.1 horizontal_flow = np.zeros_like(image0) vertical_flow = np.zeros_like(image0) kernel_x = np.array([[-1, 1], [-1, 1]]) * 0.25 kernel_y = np.array([[-1, -1], [1, 1]]) * 0.25 kernel_t = np.array([[1, 1], [1, 1]]) * 0.25 kernel_laplacian = np.array( [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]] ) for _ in range(num_iter): warped_image = warp(image0, horizontal_flow, vertical_flow) derivative_x = convolve(warped_image, kernel_x) + convolve(image1, kernel_x) derivative_y = convolve(warped_image, kernel_y) + convolve(image1, kernel_y) derivative_t = convolve(warped_image, kernel_t) + convolve(image1, -kernel_t) avg_horizontal_velocity = convolve(horizontal_flow, kernel_laplacian) avg_vertical_velocity = convolve(vertical_flow, kernel_laplacian) update = ( derivative_x * avg_horizontal_velocity + derivative_y * avg_vertical_velocity + derivative_t ) update = update / (alpha**2 + derivative_x**2 + derivative_y**2) horizontal_flow = avg_horizontal_velocity - derivative_x * update vertical_flow = avg_vertical_velocity - derivative_y * update return horizontal_flow, vertical_flow if __name__ == "__main__": import doctest doctest.testmod()
mean thresholding algorithm for image processing https en wikipedia orgwikithresholdingimageprocessing image is a grayscale pil image object mean thresholding algorithm for image processing https en wikipedia org wiki thresholding_ image_processing image is a grayscale pil image object
from PIL import Image def mean_threshold(image: Image) -> Image: height, width = image.size mean = 0 pixels = image.load() for i in range(width): for j in range(height): pixel = pixels[j, i] mean += pixel mean //= width * height for j in range(width): for i in range(height): pixels[i, j] = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": image = mean_threshold(Image.open("path_to_image").convert("L")) image.save("output_image_path")
source https github comjason9075opencvmosaicdataaug import glob import os import random from string import asciilowercase digits import cv2 import numpy as np parameters outputsize 720 1280 height width scalerange 0 4 0 6 if height or width lower than this scale drop it filtertinyscale 1 100 labeldir imgdir outputdir numberimages 250 def main none imgpaths annos getdatasetlabeldir imgdir for index in rangenumberimages idxs random samplerangelenannos 4 newimage newannos path updateimageandanno imgpaths annos idxs outputsize scalerange filterscalefiltertinyscale get random string code 7b7ad245cdff75241935e4dd860f3bad lettercode randomchars32 filename path splitos sep1 rsplit 10 fileroot foutputdirfilenamemosaiclettercode cv2 imwriteffileroot jpg newimage cv2 imwritejpegquality 85 printfsucceeded index1numberimages with filename annoslist for anno in newannos width anno3 anno1 height anno4 anno2 xcenter anno1 width 2 ycenter anno2 height 2 obj fanno0 xcenter ycenter width height annoslist appendobj with openffileroot txt w as outfile outfile writen joinline for line in annoslist def getdatasetlabeldir str imgdir str tuplelist list imgpaths labels for labelfile in glob globos path joinlabeldir txt labelname labelfile splitos sep1 rsplit 10 with openlabelfile as infile objlists infile readlines imgpath os path joinimgdir flabelname jpg boxes for objlist in objlists obj objlist rstripn split xmin floatobj1 floatobj3 2 ymin floatobj2 floatobj4 2 xmax floatobj1 floatobj3 2 ymax floatobj2 floatobj4 2 boxes appendintobj0 xmin ymin xmax ymax if not boxes continue imgpaths appendimgpath labels appendboxes return imgpaths labels def updateimageandanno allimglist list allannos list idxs listint outputsize tupleint int scalerange tuplefloat float filterscale float 0 0 tuplelist list str outputimg np zerosoutputsize0 outputsize1 3 dtypenp uint8 scalex scalerange0 random random scalerange1 scalerange0 scaley scalerange0 random random scalerange1 scalerange0 dividpointx intscalex outputsize1 dividpointy intscaley outputsize0 newanno pathlist for i index in enumerateidxs path allimglistindex pathlist appendpath imgannos allannosindex img cv2 imreadpath if i 0 topleft img cv2 resizeimg dividpointx dividpointy outputimg dividpointy dividpointx img for bbox in imgannos xmin bbox1 scalex ymin bbox2 scaley xmax bbox3 scalex ymax bbox4 scaley newanno appendbbox0 xmin ymin xmax ymax elif i 1 topright img cv2 resizeimg outputsize1 dividpointx dividpointy outputimg dividpointy dividpointx outputsize1 img for bbox in imgannos xmin scalex bbox1 1 scalex ymin bbox2 scaley xmax scalex bbox3 1 scalex ymax bbox4 scaley newanno appendbbox0 xmin ymin xmax ymax elif i 2 bottomleft img cv2 resizeimg dividpointx outputsize0 dividpointy outputimgdividpointy outputsize0 dividpointx img for bbox in imgannos xmin bbox1 scalex ymin scaley bbox2 1 scaley xmax bbox3 scalex ymax scaley bbox4 1 scaley newanno appendbbox0 xmin ymin xmax ymax else bottomright img cv2 resize img outputsize1 dividpointx outputsize0 dividpointy outputimg dividpointy outputsize0 dividpointx outputsize1 img for bbox in imgannos xmin scalex bbox1 1 scalex ymin scaley bbox2 1 scaley xmax scalex bbox3 1 scalex ymax scaley bbox4 1 scaley newanno appendbbox0 xmin ymin xmax ymax remove bounding box small than scale of filter if filterscale 0 newanno anno for anno in newanno if filterscale anno3 anno1 and filterscale anno4 anno2 return outputimg newanno pathlist0 def randomcharsnumberchar int str assert numberchar 1 the number of character should greater than 1 lettercode asciilowercase digits return joinrandom choicelettercode for in rangenumberchar if name main main printdone parameters height width if height or width lower than this scale drop it get images list and annotations list from input dir update new images and annotations save images and annotations in output dir get random string code 7b7ad245cdff75241935e4dd860f3bad label_dir type str path to label include annotation of images img_dir type str path to folder contain images return type list list of images path and labels all_img_list type list list of all images all_annos type list list of all annotations of specific image idxs type list index of image in list output_size type tuple size of output image height width scale_range type tuple range of scale image filter_scale type float the condition of downscale image and bounding box return output_img type narray image after resize new_anno type list list of new annotation after scale path 0 type string get the name of image file top left top right bottom left bottom right remove bounding box small than scale of filter automatic generate random 32 characters get random string code 7b7ad245cdff75241935e4dd860f3bad len random_chars 32 32
import glob import os import random from string import ascii_lowercase, digits import cv2 import numpy as np OUTPUT_SIZE = (720, 1280) SCALE_RANGE = (0.4, 0.6) FILTER_TINY_SCALE = 1 / 100 LABEL_DIR = "" IMG_DIR = "" OUTPUT_DIR = "" NUMBER_IMAGES = 250 def main() -> None: img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR) for index in range(NUMBER_IMAGES): idxs = random.sample(range(len(annos)), 4) new_image, new_annos, path = update_image_and_anno( img_paths, annos, idxs, OUTPUT_SIZE, SCALE_RANGE, filter_scale=FILTER_TINY_SCALE, ) letter_code = random_chars(32) file_name = path.split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}") annos_list = [] for anno in new_annos: width = anno[3] - anno[1] height = anno[4] - anno[2] x_center = anno[1] + width / 2 y_center = anno[2] + height / 2 obj = f"{anno[0]} {x_center} {y_center} {width} {height}" annos_list.append(obj) with open(f"{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") xmin = float(obj[1]) - float(obj[3]) / 2 ymin = float(obj[2]) - float(obj[4]) / 2 xmax = float(obj[1]) + float(obj[3]) / 2 ymax = float(obj[2]) + float(obj[4]) / 2 boxes.append([int(obj[0]), xmin, ymin, xmax, ymax]) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( all_img_list: list, all_annos: list, idxs: list[int], output_size: tuple[int, int], scale_range: tuple[float, float], filter_scale: float = 0.0, ) -> tuple[list, list, str]: output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8) scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) scale_y = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) divid_point_x = int(scale_x * output_size[1]) divid_point_y = int(scale_y * output_size[0]) new_anno = [] path_list = [] for i, index in enumerate(idxs): path = all_img_list[index] path_list.append(path) img_annos = all_annos[index] img = cv2.imread(path) if i == 0: img = cv2.resize(img, (divid_point_x, divid_point_y)) output_img[:divid_point_y, :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = bbox[2] * scale_y xmax = bbox[3] * scale_x ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 1: img = cv2.resize(img, (output_size[1] - divid_point_x, divid_point_y)) output_img[:divid_point_y, divid_point_x : output_size[1], :] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = bbox[2] * scale_y xmax = scale_x + bbox[3] * (1 - scale_x) ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 2: img = cv2.resize(img, (divid_point_x, output_size[0] - divid_point_y)) output_img[divid_point_y : output_size[0], :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = scale_y + bbox[2] * (1 - scale_y) xmax = bbox[3] * scale_x ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) else: img = cv2.resize( img, (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) output_img[ divid_point_y : output_size[0], divid_point_x : output_size[1], : ] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = scale_y + bbox[2] * (1 - scale_y) xmax = scale_x + bbox[3] * (1 - scale_x) ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) if filter_scale > 0: new_anno = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def random_chars(number_char: int) -> str: assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
source https computersciencewiki orgindex phpmaxpoolingpooling importing the libraries maxpooling function this function is used to perform maxpooling on the input array of 2d matriximage args arr numpy array size size of pooling matrix stride the number of pixels shifts over the input matrix returns numpy array of maxpooled matrix sample input output maxpooling1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2 2 array 6 8 14 16 maxpooling147 180 122 241 76 32 126 13 157 2 1 array241 180 241 157 compute the shape of the output matrix initialize the output matrix with zeros of shape maxpoolshape if the end of the matrix is reached break if the end of the matrix is reached break compute the maximum of the pooling matrix shift the pooling matrix by stride of column pixels shift the pooling matrix by stride of row pixels reset the column index to 0 averagepooling function this function is used to perform avgpooling on the input array of 2d matriximage args arr numpy array size size of pooling matrix stride the number of pixels shifts over the input matrix returns numpy array of avgpooled matrix sample input output avgpooling1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2 2 array 3 5 11 13 avgpooling147 180 122 241 76 32 126 13 157 2 1 array161 102 114 69 compute the shape of the output matrix initialize the output matrix with zeros of shape avgpoolshape if the end of the matrix is reached break if the end of the matrix is reached break compute the average of the pooling matrix shift the pooling matrix by stride of column pixels shift the pooling matrix by stride of row pixels reset the column index to 0 main function loading the image converting the image to numpy array and maxpooling displaying the result ensure that the image is a square matrix converting the image to numpy array and averagepooling displaying the result ensure that the image is a square matrix source https computersciencewiki org index php max pooling_ _pooling importing the libraries maxpooling function this function is used to perform maxpooling on the input array of 2d matrix image args arr numpy array size size of pooling matrix stride the number of pixels shifts over the input matrix returns numpy array of maxpooled matrix sample input output maxpooling 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2 2 array 6 8 14 16 maxpooling 147 180 122 241 76 32 126 13 157 2 1 array 241 180 241 157 compute the shape of the output matrix initialize the output matrix with zeros of shape maxpool_shape if the end of the matrix is reached break if the end of the matrix is reached break compute the maximum of the pooling matrix shift the pooling matrix by stride of column pixels shift the pooling matrix by stride of row pixels reset the column index to 0 averagepooling function this function is used to perform avgpooling on the input array of 2d matrix image args arr numpy array size size of pooling matrix stride the number of pixels shifts over the input matrix returns numpy array of avgpooled matrix sample input output avgpooling 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2 2 array 3 5 11 13 avgpooling 147 180 122 241 76 32 126 13 157 2 1 array 161 102 114 69 compute the shape of the output matrix initialize the output matrix with zeros of shape avgpool_shape if the end of the matrix is reached break if the end of the matrix is reached break compute the average of the pooling matrix shift the pooling matrix by stride of column pixels shift the pooling matrix by stride of row pixels reset the column index to 0 main function loading the image converting the image to numpy array and maxpooling displaying the result ensure that the image is a square matrix converting the image to numpy array and averagepooling displaying the result ensure that the image is a square matrix
import numpy as np from PIL import Image def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 maxpool_shape = (arr.shape[0] - size) // stride + 1 updated_arr = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: break while j < arr.shape[1]: if j + size > arr.shape[1]: break updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size]) j += stride mat_j += 1 i += stride mat_i += 1 j = 0 mat_j = 0 return updated_arr def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 avgpool_shape = (arr.shape[0] - size) // stride + 1 updated_arr = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: break while j < arr.shape[1]: if j + size > arr.shape[1]: break updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size])) j += stride mat_j += 1 i += stride mat_i += 1 j = 0 mat_j = 0 return updated_arr if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) image = Image.open("path_to_image") Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
conversion of length units available units metre kilometre megametre gigametre terametre petametre exametre zettametre yottametre usage import this file into their respective project use the function lengthconversion for conversion of length units parameters value the number of from units you want to convert fromtype from which type you want to convert totype to which type you want to convert references wikipedia reference https en wikipedia orgwikimeter wikipedia reference https en wikipedia orgwikikilometer wikipedia reference https en wikipedia orgwikiordersofmagnitudelength exponent of the factormeter conversion between astronomical length units lengthconversion1 meter kilometer 0 001 lengthconversion1 meter megametre 1e06 lengthconversion1 gigametre meter 1000000000 lengthconversion1 gigametre terametre 0 001 lengthconversion1 petametre terametre 1000 lengthconversion1 petametre exametre 0 001 lengthconversion1 terametre zettametre 1e09 lengthconversion1 yottametre zettametre 1000 lengthconversion4 wrongunit inch traceback most recent call last valueerror invalid fromtype value wrongunit conversion abbreviations are m km mm gm tm pm em zm ym exponent of the factor meter conversion between astronomical length units length_conversion 1 meter kilometer 0 001 length_conversion 1 meter megametre 1e 06 length_conversion 1 gigametre meter 1000000000 length_conversion 1 gigametre terametre 0 001 length_conversion 1 petametre terametre 1000 length_conversion 1 petametre exametre 0 001 length_conversion 1 terametre zettametre 1e 09 length_conversion 1 yottametre zettametre 1000 length_conversion 4 wrongunit inch traceback most recent call last valueerror invalid from_type value wrongunit conversion abbreviations are m km mm gm tm pm em zm ym
UNIT_SYMBOL = { "meter": "m", "kilometer": "km", "megametre": "Mm", "gigametre": "Gm", "terametre": "Tm", "petametre": "Pm", "exametre": "Em", "zettametre": "Zm", "yottametre": "Ym", } METRIC_CONVERSION = { "m": 0, "km": 3, "Mm": 6, "Gm": 9, "Tm": 12, "Pm": 15, "Em": 18, "Zm": 21, "Ym": 24, } def length_conversion(value: float, from_type: str, to_type: str) -> float: from_sanitized = from_type.lower().strip("s") to_sanitized = to_type.lower().strip("s") from_sanitized = UNIT_SYMBOL.get(from_sanitized, from_sanitized) to_sanitized = UNIT_SYMBOL.get(to_sanitized, to_sanitized) if from_sanitized not in METRIC_CONVERSION: msg = ( f"Invalid 'from_type' value: {from_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) if to_sanitized not in METRIC_CONVERSION: msg = ( f"Invalid 'to_type' value: {to_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) from_exponent = METRIC_CONVERSION[from_sanitized] to_exponent = METRIC_CONVERSION[to_sanitized] exponent = 1 if from_exponent > to_exponent: exponent = from_exponent - to_exponent else: exponent = -(to_exponent - from_exponent) return value * pow(10, exponent) if __name__ == "__main__": from doctest import testmod testmod()
convert a binary value to its decimal equivalent bintodecimal101 5 bintodecimal 1010 10 bintodecimal11101 29 bintodecimal0 0 bintodecimala traceback most recent call last valueerror nonbinary value was passed to the function bintodecimal traceback most recent call last valueerror empty string was passed to the function bintodecimal39 traceback most recent call last valueerror nonbinary value was passed to the function convert a binary value to its decimal equivalent bin_to_decimal 101 5 bin_to_decimal 1010 10 bin_to_decimal 11101 29 bin_to_decimal 0 0 bin_to_decimal a traceback most recent call last valueerror non binary value was passed to the function bin_to_decimal traceback most recent call last valueerror empty string was passed to the function bin_to_decimal 39 traceback most recent call last valueerror non binary value was passed to the function
def bin_to_decimal(bin_string: str) -> int: bin_string = str(bin_string).strip() if not bin_string: raise ValueError("Empty string was passed to the function") is_negative = bin_string[0] == "-" if is_negative: bin_string = bin_string[1:] if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") decimal_number = 0 for char in bin_string: decimal_number = 2 * decimal_number + int(char) return -decimal_number if is_negative else decimal_number if __name__ == "__main__": from doctest import testmod testmod()
converting a binary string into hexadecimal using grouping method bintohexadecimal 101011111 0x15f bintohexadecimal 1010 0x0a bintohexadecimal 11101 0x1d bintohexadecimal a traceback most recent call last valueerror nonbinary value was passed to the function bintohexadecimal traceback most recent call last valueerror empty string was passed to the function sanitising parameter exceptions converting a binary string into hexadecimal using grouping method bin_to_hexadecimal 101011111 0x15f bin_to_hexadecimal 1010 0x0a bin_to_hexadecimal 11101 0x1d bin_to_hexadecimal a traceback most recent call last valueerror non binary value was passed to the function bin_to_hexadecimal traceback most recent call last valueerror empty string was passed to the function sanitising parameter exceptions
BITS_TO_HEX = { "0000": "0", "0001": "1", "0010": "2", "0011": "3", "0100": "4", "0101": "5", "0110": "6", "0111": "7", "1000": "8", "1001": "9", "1010": "a", "1011": "b", "1100": "c", "1101": "d", "1110": "e", "1111": "f", } def bin_to_hexadecimal(binary_str: str) -> str: binary_str = str(binary_str).strip() if not binary_str: raise ValueError("Empty string was passed to the function") is_negative = binary_str[0] == "-" binary_str = binary_str[1:] if is_negative else binary_str if not all(char in "01" for char in binary_str): raise ValueError("Non-binary value was passed to the function") binary_str = ( "0" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str ) hexadecimal = [] for x in range(0, len(binary_str), 4): hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]]) hexadecimal_str = "0x" + "".join(hexadecimal) return "-" + hexadecimal_str if is_negative else hexadecimal_str if __name__ == "__main__": from doctest import testmod testmod()
the function below will convert any binary string to the octal equivalent bintooctal1111 17 bintooctal101010101010011 52523 bintooctal traceback most recent call last valueerror empty string was passed to the function bintooctala1 traceback most recent call last valueerror nonbinary value was passed to the function
def bin_to_octal(bin_string: str) -> str: if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") if not bin_string: raise ValueError("Empty string was passed to the function") oct_string = "" while len(bin_string) % 3 != 0: bin_string = "0" + bin_string bin_string_in_3_list = [ bin_string[index : index + 3] for index in range(len(bin_string)) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: oct_val = 0 for index, val in enumerate(bin_group): oct_val += int(2 ** (2 - index) * int(val)) oct_string += str(oct_val) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
convert a positive decimal number to any other representation from string import asciiuppercase alphabetvalues strordc 55 c for c in asciiuppercase def decimaltoanynum int base int str if isinstancenum float raise typeerrorint can t convert nonstring with explicit base if num 0 raise valueerrorparameter must be positive int if isinstancebase str raise typeerror str object cannot be interpreted as an integer if isinstancebase float raise typeerror float object cannot be interpreted as an integer if base in 0 1 raise valueerrorbase must be 2 if base 36 raise valueerrorbase must be 36 newvalue mod 0 div 0 while div 1 div mod divmodnum base if base 11 and 9 mod 36 actualvalue alphabetvaluesstrmod else actualvalue strmod newvalue actualvalue div num base num div if div 0 return strnewvalue 1 elif div 1 newvalue strdiv return strnewvalue 1 return newvalue 1 if name main import doctest doctest testmod for base in range2 37 for num in range1000 assert intdecimaltoanynum base base num num base decimaltoanynum base intdecimaltoanynum base base convert a positive integer to another base as str decimal_to_any 0 2 0 decimal_to_any 5 4 11 decimal_to_any 20 3 202 decimal_to_any 58 16 3a decimal_to_any 243 17 e5 decimal_to_any 34923 36 qy3 decimal_to_any 10 11 a decimal_to_any 16 16 10 decimal_to_any 36 36 10 negatives will error decimal_to_any 45 8 doctest ellipsis traceback most recent call last valueerror parameter must be positive int floats will error decimal_to_any 34 4 6 doctest ellipsis traceback most recent call last typeerror int can t convert non string with explicit base a float base will error decimal_to_any 5 2 5 doctest ellipsis traceback most recent call last typeerror float object cannot be interpreted as an integer a str base will error decimal_to_any 10 16 doctest ellipsis traceback most recent call last typeerror str object cannot be interpreted as an integer a base less than 2 will error decimal_to_any 7 0 doctest ellipsis traceback most recent call last valueerror base must be 2 a base greater than 36 will error decimal_to_any 34 37 doctest ellipsis traceback most recent call last valueerror base must be 36
from string import ascii_uppercase ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase} def decimal_to_any(num: int, base: int) -> str: if isinstance(num, float): raise TypeError("int() can't convert non-string with explicit base") if num < 0: raise ValueError("parameter must be positive int") if isinstance(base, str): raise TypeError("'str' object cannot be interpreted as an integer") if isinstance(base, float): raise TypeError("'float' object cannot be interpreted as an integer") if base in (0, 1): raise ValueError("base must be >= 2") if base > 36: raise ValueError("base must be <= 36") new_value = "" mod = 0 div = 0 while div != 1: div, mod = divmod(num, base) if base >= 11 and 9 < mod < 36: actual_value = ALPHABET_VALUES[str(mod)] else: actual_value = str(mod) new_value += actual_value div = num // base num = div if div == 0: return str(new_value[::-1]) elif div == 1: new_value += str(div) return str(new_value[::-1]) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
convert a decimal number to a binary number def decimaltobinaryiterativenum int str if isinstancenum float raise typeerror float object cannot be interpreted as an integer if isinstancenum str raise typeerror str object cannot be interpreted as an integer if num 0 return 0b0 negative false if num 0 negative true num num binary listint while num 0 binary insert0 num 2 num 1 if negative return 0b joinstre for e in binary return 0b joinstre for e in binary def decimaltobinaryrecursivehelperdecimal int str decimal intdecimal if decimal in 0 1 exit cases for the recursion return strdecimal div mod divmoddecimal 2 return decimaltobinaryrecursivehelperdiv strmod def decimaltobinaryrecursivenumber str str number strnumber strip if not number raise valueerrorno input value was provided negative if number startswith else number number lstrip if not number isnumeric raise valueerrorinput value is not an integer return fnegative0bdecimaltobinaryrecursivehelperintnumber if name main import doctest doctest testmod printdecimaltobinaryrecursiveinputinput a decimal number convert an integer decimal number to a binary number as str decimal_to_binary_iterative 0 0b0 decimal_to_binary_iterative 2 0b10 decimal_to_binary_iterative 7 0b111 decimal_to_binary_iterative 35 0b100011 negatives work too decimal_to_binary_iterative 2 0b10 other floats will error decimal_to_binary_iterative 16 16 doctest ellipsis traceback most recent call last typeerror float object cannot be interpreted as an integer strings will error as well decimal_to_binary_iterative 0xfffff doctest ellipsis traceback most recent call last typeerror str object cannot be interpreted as an integer take a positive integer value and return its binary equivalent decimal_to_binary_recursive_helper 1000 1111101000 decimal_to_binary_recursive_helper 72 1001000 decimal_to_binary_recursive_helper number traceback most recent call last valueerror invalid literal for int with base 10 number exit cases for the recursion take an integer value and raise valueerror for wrong inputs call the function above and return the output with prefix 0b 0b for positive and negative integers respectively decimal_to_binary_recursive 0 0b0 decimal_to_binary_recursive 40 0b101000 decimal_to_binary_recursive 40 0b101000 decimal_to_binary_recursive 40 8 traceback most recent call last valueerror input value is not an integer decimal_to_binary_recursive forty traceback most recent call last valueerror input value is not an integer
def decimal_to_binary_iterative(num: int) -> str: if isinstance(num, float): raise TypeError("'float' object cannot be interpreted as an integer") if isinstance(num, str): raise TypeError("'str' object cannot be interpreted as an integer") if num == 0: return "0b0" negative = False if num < 0: negative = True num = -num binary: list[int] = [] while num > 0: binary.insert(0, num % 2) num >>= 1 if negative: return "-0b" + "".join(str(e) for e in binary) return "0b" + "".join(str(e) for e in binary) def decimal_to_binary_recursive_helper(decimal: int) -> str: decimal = int(decimal) if decimal in (0, 1): return str(decimal) div, mod = divmod(decimal, 2) return decimal_to_binary_recursive_helper(div) + str(mod) def decimal_to_binary_recursive(number: str) -> str: number = str(number).strip() if not number: raise ValueError("No input value was provided") negative = "-" if number.startswith("-") else "" number = number.lstrip("-") if not number.isnumeric(): raise ValueError("Input value is not an integer") return f"{negative}0b{decimal_to_binary_recursive_helper(int(number))}" if __name__ == "__main__": import doctest doctest.testmod() print(decimal_to_binary_recursive(input("Input a decimal number: ")))
convert base 10 decimal values to hexadecimal representations set decimal value for each hexadecimal digit values 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 a 11 b 12 c 13 d 14 e 15 f def decimaltohexadecimaldecimal float str assert isinstancedecimal int float assert decimal intdecimal decimal intdecimal hexadecimal negative false if decimal 0 negative true decimal 1 while decimal 0 decimal remainder divmoddecimal 16 hexadecimal valuesremainder hexadecimal hexadecimal 0x hexadecimal if negative hexadecimal hexadecimal return hexadecimal if name main import doctest doctest testmod set decimal value for each hexadecimal digit take integer decimal value return hexadecimal representation as str beginning with 0x decimal_to_hexadecimal 5 0x5 decimal_to_hexadecimal 15 0xf decimal_to_hexadecimal 37 0x25 decimal_to_hexadecimal 255 0xff decimal_to_hexadecimal 4096 0x1000 decimal_to_hexadecimal 999098 0xf3eba negatives work too decimal_to_hexadecimal 256 0x100 floats are acceptable if equivalent to an int decimal_to_hexadecimal 17 0 0x11 other floats will error decimal_to_hexadecimal 16 16 doctest ellipsis traceback most recent call last assertionerror strings will error as well decimal_to_hexadecimal 0xfffff doctest ellipsis traceback most recent call last assertionerror results are the same when compared to python s default hex function decimal_to_hexadecimal 256 hex 256 true
values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal: float) -> str: assert isinstance(decimal, (int, float)) assert decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
convert a decimal number to an octal number import math modified from https github comthealgorithmsjavascriptblobmasterconversionsdecimaltooctal js def decimaltooctalnum int str octal 0 counter 0 while num 0 remainder num 8 octal octal remainder math floormath pow10 counter counter 1 num math floornum 8 basically 8 without remainder if any this formatting removes trailing 0 from octal return f0ointoctal def main none modified from https github com thealgorithms javascript blob master conversions decimaltooctal js convert a decimal number to an octal number all decimal_to_octal i oct i for i in 0 2 8 64 65 216 255 256 512 true basically 8 without remainder if any this formatting removes trailing 0 from octal print octal equivalents of decimal numbers 2 10 101 330 1000
import math def decimal_to_octal(num: int) -> str: octal = 0 counter = 0 while num > 0: remainder = num % 8 octal = octal + (remainder * math.floor(math.pow(10, counter))) counter += 1 num = math.floor(num / 8) return f"0o{int(octal)}" def main() -> None: print("\n2 in octal is:") print(decimal_to_octal(2)) print("\n8 in octal is:") print(decimal_to_octal(8)) print("\n65 in octal is:") print(decimal_to_octal(65)) print("\n216 in octal is:") print(decimal_to_octal(216)) print("\n512 in octal is:") print(decimal_to_octal(512)) print("\n") if __name__ == "__main__": main()
conversion of energy units available units joule kilojoule megajoule gigajoule wattsecond watthour kilowatthour newtonmeter calorienutr kilocalorienutr electronvolt britishthermalunitit footpound usage import this file into their respective project use the function energyconversion for conversion of energy units parameters fromtype from which type you want to convert totype to which type you want to convert value the value which you want to convert references wikipedia reference https en wikipedia orgwikiunitsofenergy wikipedia reference https en wikipedia orgwikijoule wikipedia reference https en wikipedia orgwikikilowatthour wikipedia reference https en wikipedia orgwikinewtonmetre wikipedia reference https en wikipedia orgwikicalorie wikipedia reference https en wikipedia orgwikielectronvolt wikipedia reference https en wikipedia orgwikibritishthermalunit wikipedia reference https en wikipedia orgwikifootpoundenergy unit converter reference https www unitconverters netenergyconverter html conversion of energy units energyconversionjoule joule 1 1 0 energyconversionjoule kilojoule 1 0 001 energyconversionjoule megajoule 1 1e06 energyconversionjoule gigajoule 1 1e09 energyconversionjoule wattsecond 1 1 0 energyconversionjoule watthour 1 0 0002777777777777778 energyconversionjoule kilowatthour 1 2 7777777777777776e07 energyconversionjoule newtonmeter 1 1 0 energyconversionjoule calorienutr 1 0 00023884589662749592 energyconversionjoule kilocalorienutr 1 2 388458966274959e07 energyconversionjoule electronvolt 1 6 241509074460763e18 energyconversionjoule britishthermalunitit 1 0 0009478171226670134 energyconversionjoule footpound 1 0 7375621211696556 energyconversionjoule megajoule 1000 0 001 energyconversioncalorienutr kilocalorienutr 1000 1 0 energyconversionkilowatthour joule 10 36000000 0 energyconversionbritishthermalunitit footpound 1 778 1692306784539 energyconversionwatthour joule a doctest ellipsis traceback most recent call last typeerror unsupported operand types for str and float energyconversionwrongunit joule 1 doctest ellipsis traceback most recent call last valueerror incorrect fromtype or totype value wrongunit joule valid values are joule footpound energyconversionjoule wrongunit 1 doctest ellipsis traceback most recent call last valueerror incorrect fromtype or totype value joule wrongunit valid values are joule footpound energyconversion123 abc 1 doctest ellipsis traceback most recent call last valueerror incorrect fromtype or totype value 123 abc valid values are joule footpound conversion of energy units energy_conversion joule joule 1 1 0 energy_conversion joule kilojoule 1 0 001 energy_conversion joule megajoule 1 1e 06 energy_conversion joule gigajoule 1 1e 09 energy_conversion joule wattsecond 1 1 0 energy_conversion joule watthour 1 0 0002777777777777778 energy_conversion joule kilowatthour 1 2 7777777777777776e 07 energy_conversion joule newtonmeter 1 1 0 energy_conversion joule calorie_nutr 1 0 00023884589662749592 energy_conversion joule kilocalorie_nutr 1 2 388458966274959e 07 energy_conversion joule electronvolt 1 6 241509074460763e 18 energy_conversion joule britishthermalunit_it 1 0 0009478171226670134 energy_conversion joule footpound 1 0 7375621211696556 energy_conversion joule megajoule 1000 0 001 energy_conversion calorie_nutr kilocalorie_nutr 1000 1 0 energy_conversion kilowatthour joule 10 36000000 0 energy_conversion britishthermalunit_it footpound 1 778 1692306784539 energy_conversion watthour joule a doctest ellipsis traceback most recent call last typeerror unsupported operand type s for str and float energy_conversion wrongunit joule 1 doctest ellipsis traceback most recent call last valueerror incorrect from_type or to_type value wrongunit joule valid values are joule footpound energy_conversion joule wrongunit 1 doctest ellipsis traceback most recent call last valueerror incorrect from_type or to_type value joule wrongunit valid values are joule footpound energy_conversion 123 abc 1 doctest ellipsis traceback most recent call last valueerror incorrect from_type or to_type value 123 abc valid values are joule footpound
ENERGY_CONVERSION: dict[str, float] = { "joule": 1.0, "kilojoule": 1_000, "megajoule": 1_000_000, "gigajoule": 1_000_000_000, "wattsecond": 1.0, "watthour": 3_600, "kilowatthour": 3_600_000, "newtonmeter": 1.0, "calorie_nutr": 4_186.8, "kilocalorie_nutr": 4_186_800.00, "electronvolt": 1.602_176_634e-19, "britishthermalunit_it": 1_055.055_85, "footpound": 1.355_818, } def energy_conversion(from_type: str, to_type: str, value: float) -> float: if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: msg = ( f"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Valid values are: {', '.join(ENERGY_CONVERSION)}" ) raise ValueError(msg) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
given a string columntitle that represents the column title in an excel sheet return its corresponding column number exceltitletocolumna 1 exceltitletocolumnb 2 exceltitletocolumnab 28 exceltitletocolumnz 26 given a string column_title that represents the column title in an excel sheet return its corresponding column number excel_title_to_column a 1 excel_title_to_column b 2 excel_title_to_column ab 28 excel_title_to_column z 26
def excel_title_to_column(column_title: str) -> int: assert column_title.isupper() answer = 0 index = len(column_title) - 1 power = 0 while index >= 0: value = (ord(column_title[index]) - 64) * pow(26, power) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
convert a hexadecimal value to its binary equivalent https stackoverflow comquestions1425493converthextobinary here we have used the bitwise right shift operator shifts the bits of the number to the right and fills 0 on voids left as a result similar effect as of dividing the number with some power of two example a 10 a 1 5 hextobinac 10101100 hextobin9a4 100110100100 hextobin 12f 100101111 hextobinffff 1111111111111111 hextobinffff 1111111111111111 hextobinff traceback most recent call last valueerror invalid value was passed to the function hextobin traceback most recent call last valueerror no value was passed to the function convert a hexadecimal value to its binary equivalent https stackoverflow com questions 1425493 convert hex to binary here we have used the bitwise right shift operator shifts the bits of the number to the right and fills 0 on voids left as a result similar effect as of dividing the number with some power of two example a 10 a 1 5 hex_to_bin ac 10101100 hex_to_bin 9a4 100110100100 hex_to_bin 12f 100101111 hex_to_bin ffff 1111111111111111 hex_to_bin ffff 1111111111111111 hex_to_bin f f traceback most recent call last valueerror invalid value was passed to the function hex_to_bin traceback most recent call last valueerror no value was passed to the function
def hex_to_bin(hex_num: str) -> int: hex_num = hex_num.strip() if not hex_num: raise ValueError("No value was passed to the function") is_negative = hex_num[0] == "-" if is_negative: hex_num = hex_num[1:] try: int_num = int(hex_num, 16) except ValueError: raise ValueError("Invalid value was passed to the function") bin_str = "" while int_num > 0: bin_str = str(int_num % 2) + bin_str int_num >>= 1 return int(("-" + bin_str) if is_negative else bin_str) if __name__ == "__main__": import doctest doctest.testmod()
convert a hexadecimal value to its decimal equivalent https www programiz compythonprogrammingmethodsbuiltinhex hextodecimala 10 hextodecimal12f 303 hextodecimal 12f 303 hextodecimalffff 65535 hextodecimalff 255 hextodecimalff traceback most recent call last valueerror nonhexadecimal value was passed to the function hextodecimal traceback most recent call last valueerror empty string was passed to the function hextodecimal12m traceback most recent call last valueerror nonhexadecimal value was passed to the function use 2 to strip off the leading 0x convert a hexadecimal value to its decimal equivalent https www programiz com python programming methods built in hex hex_to_decimal a 10 hex_to_decimal 12f 303 hex_to_decimal 12f 303 hex_to_decimal ffff 65535 hex_to_decimal ff 255 hex_to_decimal f f traceback most recent call last valueerror non hexadecimal value was passed to the function hex_to_decimal traceback most recent call last valueerror empty string was passed to the function hex_to_decimal 12m traceback most recent call last valueerror non hexadecimal value was passed to the function
hex_table = {hex(i)[2:]: i for i in range(16)} def hex_to_decimal(hex_string: str) -> int: hex_string = hex_string.strip().lower() if not hex_string: raise ValueError("Empty string was passed to the function") is_negative = hex_string[0] == "-" if is_negative: hex_string = hex_string[1:] if not all(char in hex_table for char in hex_string): raise ValueError("Non-hexadecimal value was passed to the function") decimal_number = 0 for char in hex_string: decimal_number = 16 * decimal_number + hex_table[char] return -decimal_number if is_negative else decimal_number if __name__ == "__main__": from doctest import testmod testmod()
https www geeksforgeeks orgconvertipaddresstointegerandviceversa convert an ipv4 address to its decimal representation args ipaddress a string representing an ipv4 address e g 192 168 0 1 returns int the decimal representation of the ip address ipv4todecimal192 168 0 1 3232235521 ipv4todecimal10 0 0 255 167772415 ipv4todecimal10 0 255 traceback most recent call last valueerror invalid ipv4 address format ipv4todecimal10 0 0 256 traceback most recent call last valueerror invalid ipv4 octet 256 altipv4todecimal192 168 0 1 3232235521 altipv4todecimal10 0 0 255 167772415 convert a decimal representation of an ip address to its ipv4 format args decimalipv4 an integer representing the decimal ip address returns the ipv4 representation of the decimal ip address decimaltoipv43232235521 192 168 0 1 decimaltoipv4167772415 10 0 0 255 decimaltoipv41 traceback most recent call last valueerror invalid decimal ipv4 address https www geeksforgeeks org convert ip address to integer and vice versa convert an ipv4 address to its decimal representation args ip_address a string representing an ipv4 address e g 192 168 0 1 returns int the decimal representation of the ip address ipv4_to_decimal 192 168 0 1 3232235521 ipv4_to_decimal 10 0 0 255 167772415 ipv4_to_decimal 10 0 255 traceback most recent call last valueerror invalid ipv4 address format ipv4_to_decimal 10 0 0 256 traceback most recent call last valueerror invalid ipv4 octet 256 noqa em102 alt_ipv4_to_decimal 192 168 0 1 3232235521 alt_ipv4_to_decimal 10 0 0 255 167772415 convert a decimal representation of an ip address to its ipv4 format args decimal_ipv4 an integer representing the decimal ip address returns the ipv4 representation of the decimal ip address decimal_to_ipv4 3232235521 192 168 0 1 decimal_to_ipv4 167772415 10 0 0 255 decimal_to_ipv4 1 traceback most recent call last valueerror invalid decimal ipv4 address
def ipv4_to_decimal(ipv4_address: str) -> int: octets = [int(octet) for octet in ipv4_address.split(".")] if len(octets) != 4: raise ValueError("Invalid IPv4 address format") decimal_ipv4 = 0 for octet in octets: if not 0 <= octet <= 255: raise ValueError(f"Invalid IPv4 octet {octet}") decimal_ipv4 = (decimal_ipv4 << 8) + int(octet) return decimal_ipv4 def alt_ipv4_to_decimal(ipv4_address: str) -> int: return int("0x" + "".join(f"{int(i):02x}" for i in ipv4_address.split(".")), 16) def decimal_to_ipv4(decimal_ipv4: int) -> str: if not (0 <= decimal_ipv4 <= 4294967295): raise ValueError("Invalid decimal IPv4 address") ip_parts = [] for _ in range(4): ip_parts.append(str(decimal_ipv4 & 255)) decimal_ipv4 >>= 8 return ".".join(reversed(ip_parts)) if __name__ == "__main__": import doctest doctest.testmod()
conversion of length units available units metre kilometre feet inch centimeter yard foot mile millimeter usage import this file into their respective project use the function lengthconversion for conversion of length units parameters value the number of from units you want to convert fromtype from which type you want to convert totype to which type you want to convert references wikipedia reference https en wikipedia orgwikimeter wikipedia reference https en wikipedia orgwikikilometer wikipedia reference https en wikipedia orgwikifeet wikipedia reference https en wikipedia orgwikiinch wikipedia reference https en wikipedia orgwikicentimeter wikipedia reference https en wikipedia orgwikiyard wikipedia reference https en wikipedia orgwikifoot wikipedia reference https en wikipedia orgwikimile wikipedia reference https en wikipedia orgwikimillimeter conversion between length units lengthconversion4 meter feet 13 12336 lengthconversion4 m ft 13 12336 lengthconversion1 meter kilometer 0 001 lengthconversion1 kilometer inch 39370 1 lengthconversion3 kilometer mile 1 8641130000000001 lengthconversion2 feet meter 0 6096 lengthconversion4 feet yard 1 333329312 lengthconversion1 inch meter 0 0254 lengthconversion2 inch mile 3 15656468e05 lengthconversion2 centimeter millimeter 20 0 lengthconversion2 centimeter yard 0 0218722 lengthconversion4 yard meter 3 6576 lengthconversion4 yard kilometer 0 0036576 lengthconversion3 foot meter 0 9144000000000001 lengthconversion3 foot inch 36 00001944 lengthconversion4 mile kilometer 6 43736 lengthconversion2 miles inches 126719 753468 lengthconversion3 millimeter centimeter 0 3 lengthconversion3 mm in 0 1181103 lengthconversion4 wrongunit inch traceback most recent call last valueerror invalid fromtype value wrongunit conversion abbreviations are mm cm m km in ft yd mi trailing s has been stripped off conversion between length units length_conversion 4 meter feet 13 12336 length_conversion 4 m ft 13 12336 length_conversion 1 meter kilometer 0 001 length_conversion 1 kilometer inch 39370 1 length_conversion 3 kilometer mile 1 8641130000000001 length_conversion 2 feet meter 0 6096 length_conversion 4 feet yard 1 333329312 length_conversion 1 inch meter 0 0254 length_conversion 2 inch mile 3 15656468e 05 length_conversion 2 centimeter millimeter 20 0 length_conversion 2 centimeter yard 0 0218722 length_conversion 4 yard meter 3 6576 length_conversion 4 yard kilometer 0 0036576 length_conversion 3 foot meter 0 9144000000000001 length_conversion 3 foot inch 36 00001944 length_conversion 4 mile kilometer 6 43736 length_conversion 2 miles inches 126719 753468 length_conversion 3 millimeter centimeter 0 3 length_conversion 3 mm in 0 1181103 length_conversion 4 wrongunit inch traceback most recent call last valueerror invalid from_type value wrongunit conversion abbreviations are mm cm m km in ft yd mi
from typing import NamedTuple class FromTo(NamedTuple): from_factor: float to_factor: float TYPE_CONVERSION = { "millimeter": "mm", "centimeter": "cm", "meter": "m", "kilometer": "km", "inch": "in", "inche": "in", "feet": "ft", "foot": "ft", "yard": "yd", "mile": "mi", } METRIC_CONVERSION = { "mm": FromTo(0.001, 1000), "cm": FromTo(0.01, 100), "m": FromTo(1, 1), "km": FromTo(1000, 0.001), "in": FromTo(0.0254, 39.3701), "ft": FromTo(0.3048, 3.28084), "yd": FromTo(0.9144, 1.09361), "mi": FromTo(1609.34, 0.000621371), } def length_conversion(value: float, from_type: str, to_type: str) -> float: new_from = from_type.lower().rstrip("s") new_from = TYPE_CONVERSION.get(new_from, new_from) new_to = to_type.lower().rstrip("s") new_to = TYPE_CONVERSION.get(new_to, new_to) if new_from not in METRIC_CONVERSION: msg = ( f"Invalid 'from_type' value: {from_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) if new_to not in METRIC_CONVERSION: msg = ( f"Invalid 'to_type' value: {to_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) return ( value * METRIC_CONVERSION[new_from].from_factor * METRIC_CONVERSION[new_to].to_factor ) if __name__ == "__main__": import doctest doctest.testmod()
functions useful for doing molecular chemistry molaritytonormality molestopressure molestovolume pressureandvolumetotemperature convert molarity to normality volume is taken in litres wikipedia reference https en wikipedia orgwikiequivalentconcentration wikipedia reference https en wikipedia orgwikimolarconcentration molaritytonormality2 3 1 0 31 20 molaritytonormality4 11 4 5 7 8 convert moles to pressure ideal gas laws are used temperature is taken in kelvin volume is taken in litres pressure has atm as si unit wikipedia reference https en wikipedia orgwikigaslaws wikipedia reference https en wikipedia orgwikipressure wikipedia reference https en wikipedia orgwikitemperature molestopressure0 82 3 300 90 molestopressure8 2 5 200 10 convert moles to volume ideal gas laws are used temperature is taken in kelvin volume is taken in litres pressure has atm as si unit wikipedia reference https en wikipedia orgwikigaslaws wikipedia reference https en wikipedia orgwikipressure wikipedia reference https en wikipedia orgwikitemperature molestovolume0 82 3 300 90 molestovolume8 2 5 200 10 convert pressure and volume to temperature ideal gas laws are used temperature is taken in kelvin volume is taken in litres pressure has atm as si unit wikipedia reference https en wikipedia orgwikigaslaws wikipedia reference https en wikipedia orgwikipressure wikipedia reference https en wikipedia orgwikitemperature pressureandvolumetotemperature0 82 1 2 20 pressureandvolumetotemperature8 2 5 3 60 convert molarity to normality volume is taken in litres wikipedia reference https en wikipedia org wiki equivalent_concentration wikipedia reference https en wikipedia org wiki molar_concentration molarity_to_normality 2 3 1 0 31 20 molarity_to_normality 4 11 4 5 7 8 convert moles to pressure ideal gas laws are used temperature is taken in kelvin volume is taken in litres pressure has atm as si unit wikipedia reference https en wikipedia org wiki gas_laws wikipedia reference https en wikipedia org wiki pressure wikipedia reference https en wikipedia org wiki temperature moles_to_pressure 0 82 3 300 90 moles_to_pressure 8 2 5 200 10 convert moles to volume ideal gas laws are used temperature is taken in kelvin volume is taken in litres pressure has atm as si unit wikipedia reference https en wikipedia org wiki gas_laws wikipedia reference https en wikipedia org wiki pressure wikipedia reference https en wikipedia org wiki temperature moles_to_volume 0 82 3 300 90 moles_to_volume 8 2 5 200 10 convert pressure and volume to temperature ideal gas laws are used temperature is taken in kelvin volume is taken in litres pressure has atm as si unit wikipedia reference https en wikipedia org wiki gas_laws wikipedia reference https en wikipedia org wiki pressure wikipedia reference https en wikipedia org wiki temperature pressure_and_volume_to_temperature 0 82 1 2 20 pressure_and_volume_to_temperature 8 2 5 3 60
def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: return round(float(moles / volume) * nfactor) def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: return round(float((moles * 0.0821 * temperature) / (volume))) def moles_to_volume(pressure: float, moles: float, temperature: float) -> float: return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest doctest.testmod()
bama charan chhandogi https github combamacharanchhandogi description convert a octal number to binary references for better understanding https en wikipedia orgwikibinarynumber https en wikipedia orgwikioctal convert an octal number to binary octaltobinary17 001111 octaltobinary7 111 octaltobinaryav traceback most recent call last valueerror nonoctal value was passed to the function octaltobinary traceback most recent call last valueerror nonoctal value was passed to the function octaltobinary traceback most recent call last valueerror empty string was passed to the function convert an octal number to binary octal_to_binary 17 001111 octal_to_binary 7 111 octal_to_binary av traceback most recent call last valueerror non octal value was passed to the function octal_to_binary traceback most recent call last valueerror non octal value was passed to the function octal_to_binary traceback most recent call last valueerror empty string was passed to the function
def octal_to_binary(octal_number: str) -> str: if not octal_number: raise ValueError("Empty string was passed to the function") binary_number = "" octal_digits = "01234567" for digit in octal_number: if digit not in octal_digits: raise ValueError("Non-octal value was passed to the function") binary_digit = "" value = int(digit) for _ in range(3): binary_digit = str(value % 2) + binary_digit value //= 2 binary_number += binary_digit return binary_number if __name__ == "__main__": import doctest doctest.testmod()
convert a octal value to its decimal equivalent octtodecimal traceback most recent call last valueerror empty string was passed to the function octtodecimal traceback most recent call last valueerror nonoctal value was passed to the function octtodecimale traceback most recent call last valueerror nonoctal value was passed to the function octtodecimal8 traceback most recent call last valueerror nonoctal value was passed to the function octtodecimale traceback most recent call last valueerror nonoctal value was passed to the function octtodecimal8 traceback most recent call last valueerror nonoctal value was passed to the function octtodecimal1 1 octtodecimal1 1 octtodecimal12 10 octtodecimal 12 10 octtodecimal45 37 octtodecimal traceback most recent call last valueerror nonoctal value was passed to the function octtodecimal0 0 octtodecimal4055 2093 octtodecimal20fm traceback most recent call last valueerror nonoctal value was passed to the function octtodecimal traceback most recent call last valueerror empty string was passed to the function octtodecimal19 traceback most recent call last valueerror nonoctal value was passed to the function convert a octal value to its decimal equivalent oct_to_decimal traceback most recent call last valueerror empty string was passed to the function oct_to_decimal traceback most recent call last valueerror non octal value was passed to the function oct_to_decimal e traceback most recent call last valueerror non octal value was passed to the function oct_to_decimal 8 traceback most recent call last valueerror non octal value was passed to the function oct_to_decimal e traceback most recent call last valueerror non octal value was passed to the function oct_to_decimal 8 traceback most recent call last valueerror non octal value was passed to the function oct_to_decimal 1 1 oct_to_decimal 1 1 oct_to_decimal 12 10 oct_to_decimal 12 10 oct_to_decimal 45 37 oct_to_decimal traceback most recent call last valueerror non octal value was passed to the function oct_to_decimal 0 0 oct_to_decimal 4055 2093 oct_to_decimal 2 0fm traceback most recent call last valueerror non octal value was passed to the function oct_to_decimal traceback most recent call last valueerror empty string was passed to the function oct_to_decimal 19 traceback most recent call last valueerror non octal value was passed to the function
def oct_to_decimal(oct_string: str) -> int: oct_string = str(oct_string).strip() if not oct_string: raise ValueError("Empty string was passed to the function") is_negative = oct_string[0] == "-" if is_negative: oct_string = oct_string[1:] if not oct_string.isdigit() or not all(0 <= int(char) <= 7 for char in oct_string): raise ValueError("Non-octal value was passed to the function") decimal_number = 0 for char in oct_string: decimal_number = 8 * decimal_number + int(char) if is_negative: decimal_number = -decimal_number return decimal_number if __name__ == "__main__": from doctest import testmod testmod()
convert an octal number to hexadecimal number for more information https en wikipedia orgwikioctal octaltohex100 0x40 octaltohex235 0x9d octaltohex17 traceback most recent call last typeerror expected a string as input octaltohexav traceback most recent call last valueerror not a valid octal number octaltohex traceback most recent call last valueerror empty string was passed to the function main tests convert an octal number to hexadecimal number for more information https en wikipedia org wiki octal octal_to_hex 100 0x40 octal_to_hex 235 0x9d octal_to_hex 17 traceback most recent call last typeerror expected a string as input octal_to_hex av traceback most recent call last valueerror not a valid octal number octal_to_hex traceback most recent call last valueerror empty string was passed to the function main tests
def octal_to_hex(octal: str) -> str: if not isinstance(octal, str): raise TypeError("Expected a string as input") if octal.startswith("0o"): octal = octal[2:] if octal == "": raise ValueError("Empty string was passed to the function") if any(char not in "01234567" for char in octal): raise ValueError("Not a Valid Octal Number") decimal = 0 for char in octal: decimal <<= 3 decimal |= int(char) hex_char = "0123456789ABCDEF" revhex = "" while decimal: revhex += hex_char[decimal & 15] decimal >>= 4 return "0x" + revhex[::-1] if __name__ == "__main__": import doctest doctest.testmod() nums = ["030", "100", "247", "235", "007"] for num in nums: hexadecimal = octal_to_hex(num) expected = "0x" + hex(int(num, 8))[2:].upper() assert hexadecimal == expected print(f"Hex of '0o{num}' is: {hexadecimal}") print(f"Expected was: {expected}") print("---")
convert international system of units si and binary prefixes wikipedia reference https en wikipedia orgwikibinaryprefix wikipedia reference https en wikipedia orgwikiinternationalsystemofunits convertsiprefix1 siunit giga siunit mega 1000 convertsiprefix1 siunit mega siunit giga 0 001 convertsiprefix1 siunit kilo siunit kilo 1 convertsiprefix1 giga mega 1000 convertsiprefix1 giga mega 1000 wikipedia reference https en wikipedia orgwikimetricprefix convertbinaryprefix1 binaryunit giga binaryunit mega 1024 convertbinaryprefix1 binaryunit mega binaryunit giga 0 0009765625 convertbinaryprefix1 binaryunit kilo binaryunit kilo 1 convertbinaryprefix1 giga mega 1024 convertbinaryprefix1 giga mega 1024 wikipedia reference https en wikipedia org wiki binary_prefix wikipedia reference https en wikipedia org wiki international_system_of_units convert_si_prefix 1 siunit giga siunit mega 1000 convert_si_prefix 1 siunit mega siunit giga 0 001 convert_si_prefix 1 siunit kilo siunit kilo 1 convert_si_prefix 1 giga mega 1000 convert_si_prefix 1 giga mega 1000 wikipedia reference https en wikipedia org wiki metric_prefix convert_binary_prefix 1 binaryunit giga binaryunit mega 1024 convert_binary_prefix 1 binaryunit mega binaryunit giga 0 0009765625 convert_binary_prefix 1 binaryunit kilo binaryunit kilo 1 convert_binary_prefix 1 giga mega 1024 convert_binary_prefix 1 giga mega 1024
from __future__ import annotations from enum import Enum class SIUnit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class BinaryUnit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: str | SIUnit, unknown_prefix: str | SIUnit, ) -> float: if isinstance(known_prefix, str): known_prefix = SIUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = SIUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 10 ** (known_prefix.value - unknown_prefix.value) ) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: str | BinaryUnit, unknown_prefix: str | BinaryUnit, ) -> float: if isinstance(known_prefix, str): known_prefix = BinaryUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = BinaryUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
manuel di lullo https github commanueldilullo description convert a number to use the correct si or binary unit prefix inspired by prefixconversion py file in this repository by lancepyles url https en wikipedia orgwikimetricprefixlistofsiprefixes url https en wikipedia orgwikibinaryprefix create a generic variable that can be enum or any subclass returns a dictionary with only the elements of this enum that has a positive value from itertools import islice positive siunit getpositive inc iterpositive items dictisliceinc lenpositive 2 yotta 24 zetta 21 exa 18 peta 15 tera 12 dictinc giga 9 mega 6 kilo 3 hecto 2 deca 1 returns a dictionary with only the elements of this enum that has a negative value example from itertools import islice negative siunit getnegative inc iternegative items dictisliceinc lennegative 2 deci 1 centi 2 milli 3 micro 6 nano 9 dictinc pico 12 femto 15 atto 18 zepto 21 yocto 24 function that converts a number to his version with si prefix input value an integer example addsiprefix10000 10 0 kilo function that converts a number to his version with binary prefix input value an integer example addbinaryprefix65536 64 0 kilo create a generic variable that can be enum or any subclass returns a dictionary with only the elements of this enum that has a positive value from itertools import islice positive siunit get_positive inc iter positive items dict islice inc len positive 2 yotta 24 zetta 21 exa 18 peta 15 tera 12 dict inc giga 9 mega 6 kilo 3 hecto 2 deca 1 returns a dictionary with only the elements of this enum that has a negative value example from itertools import islice negative siunit get_negative inc iter negative items dict islice inc len negative 2 deci 1 centi 2 milli 3 micro 6 nano 9 dict inc pico 12 femto 15 atto 18 zepto 21 yocto 24 function that converts a number to his version with si prefix input value an integer example add_si_prefix 10000 10 0 kilo function that converts a number to his version with binary prefix input value an integer example add_binary_prefix 65536 64 0 kilo
from __future__ import annotations from enum import Enum, unique from typing import TypeVar T = TypeVar("T", bound="Enum") @unique class BinaryUnit(Enum): yotta = 80 zetta = 70 exa = 60 peta = 50 tera = 40 giga = 30 mega = 20 kilo = 10 @unique class SIUnit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 @classmethod def get_positive(cls: type[T]) -> dict: return {unit.name: unit.value for unit in cls if unit.value > 0} @classmethod def get_negative(cls: type[T]) -> dict: return {unit.name: unit.value for unit in cls if unit.value < 0} def add_si_prefix(value: float) -> str: prefixes = SIUnit.get_positive() if value > 0 else SIUnit.get_negative() for name_prefix, value_prefix in prefixes.items(): numerical_part = value / (10**value_prefix) if numerical_part > 1: return f"{numerical_part!s} {name_prefix}" return str(value) def add_binary_prefix(value: float) -> str: for prefix in BinaryUnit: numerical_part = value / (2**prefix.value) if numerical_part > 1: return f"{numerical_part!s} {prefix.name}" return str(value) if __name__ == "__main__": import doctest doctest.testmod()
conversion of pressure units available units pascal bar kilopascal megapascal psipound per square inch inhgin mercury column torr atm usage import this file into their respective project use the function pressureconversion for conversion of pressure units parameters value the number of from units you want to convert fromtype from which type you want to convert totype to which type you want to convert references wikipedia reference https en wikipedia orgwikipascalunit wikipedia reference https en wikipedia orgwikipoundpersquareinch wikipedia reference https en wikipedia orgwikiinchofmercury wikipedia reference https en wikipedia orgwikitorr https en wikipedia orgwikistandardatmosphereunit https msestudent comwhataretheunitsofpressure https www unitconverters netpressureconverter html conversion between pressure units pressureconversion4 atm pascal 405300 pressureconversion1 pascal psi 0 00014401981999999998 pressureconversion1 bar atm 0 986923 pressureconversion3 kilopascal bar 0 029999991892499998 pressureconversion2 megapascal psi 290 074434314 pressureconversion4 psi torr 206 85984 pressureconversion1 inhg atm 0 0334211 pressureconversion1 torr psi 0 019336718261000002 pressureconversion4 wrongunit atm traceback most recent call last valueerror invalid fromtype value wrongunit supported values are atm pascal bar kilopascal megapascal psi inhg torr conversion between pressure units pressure_conversion 4 atm pascal 405300 pressure_conversion 1 pascal psi 0 00014401981999999998 pressure_conversion 1 bar atm 0 986923 pressure_conversion 3 kilopascal bar 0 029999991892499998 pressure_conversion 2 megapascal psi 290 074434314 pressure_conversion 4 psi torr 206 85984 pressure_conversion 1 inhg atm 0 0334211 pressure_conversion 1 torr psi 0 019336718261000002 pressure_conversion 4 wrongunit atm traceback most recent call last valueerror invalid from_type value wrongunit supported values are atm pascal bar kilopascal megapascal psi inhg torr
from typing import NamedTuple class FromTo(NamedTuple): from_factor: float to_factor: float PRESSURE_CONVERSION = { "atm": FromTo(1, 1), "pascal": FromTo(0.0000098, 101325), "bar": FromTo(0.986923, 1.01325), "kilopascal": FromTo(0.00986923, 101.325), "megapascal": FromTo(9.86923, 0.101325), "psi": FromTo(0.068046, 14.6959), "inHg": FromTo(0.0334211, 29.9213), "torr": FromTo(0.00131579, 760), } def pressure_conversion(value: float, from_type: str, to_type: str) -> float: if from_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) if to_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) return ( value * PRESSURE_CONVERSION[from_type].from_factor * PRESSURE_CONVERSION[to_type].to_factor ) if __name__ == "__main__": import doctest doctest.testmod()
simple rgb to cmyk conversion returns percentages of cmyk paint https www programmingalgorithms comalgorithmrgbtocmyk note this is a very popular algorithm that converts colors linearly and gives only approximate results actual preparation for printing requires advanced color conversion considering the color profiles and parameters of the target device rgbtocmyk255 200 a traceback most recent call last valueerror expected int found class int class int class str rgbtocmyk255 255 999 traceback most recent call last valueerror expected int of the range 0 255 rgbtocmyk255 255 255 white 0 0 0 0 rgbtocmyk128 128 128 gray 0 0 0 50 rgbtocmyk0 0 0 black 0 0 0 100 rgbtocmyk255 0 0 red 0 100 100 0 rgbtocmyk0 255 0 green 100 0 100 0 rgbtocmyk0 0 255 blue 100 100 0 0 changing range from 0 255 to 0 1 simple rgb to cmyk conversion returns percentages of cmyk paint https www programmingalgorithms com algorithm rgb to cmyk note this is a very popular algorithm that converts colors linearly and gives only approximate results actual preparation for printing requires advanced color conversion considering the color profiles and parameters of the target device rgb_to_cmyk 255 200 a traceback most recent call last valueerror expected int found class int class int class str rgb_to_cmyk 255 255 999 traceback most recent call last valueerror expected int of the range 0 255 rgb_to_cmyk 255 255 255 white 0 0 0 0 rgb_to_cmyk 128 128 128 gray 0 0 0 50 rgb_to_cmyk 0 0 0 black 0 0 0 100 rgb_to_cmyk 255 0 0 red 0 100 100 0 rgb_to_cmyk 0 255 0 green 100 0 100 0 rgb_to_cmyk 0 0 255 blue 100 100 0 0 changing range from 0 255 to 0 1 pure black
def rgb_to_cmyk(r_input: int, g_input: int, b_input: int) -> tuple[int, int, int, int]: if ( not isinstance(r_input, int) or not isinstance(g_input, int) or not isinstance(b_input, int) ): msg = f"Expected int, found {type(r_input), type(g_input), type(b_input)}" raise ValueError(msg) if not 0 <= r_input < 256 or not 0 <= g_input < 256 or not 0 <= b_input < 256: raise ValueError("Expected int of the range 0..255") r = r_input / 255 g = g_input / 255 b = b_input / 255 k = 1 - max(r, g, b) if k == 1: return 0, 0, 0, 100 c = round(100 * (1 - r - k) / (1 - k)) m = round(100 * (1 - g - k) / (1 - k)) y = round(100 * (1 - b - k) / (1 - k)) k = round(100 * k) return c, m, y, k if __name__ == "__main__": from doctest import testmod testmod()
the rgb color model is an additive color model in which red green and blue light are added together in various ways to reproduce a broad array of colors the name of the model comes from the initials of the three additive primary colors red green and blue meanwhile the hsv representation models how colors appear under light in it colors are represented using three components hue saturation and brightnessvalue this file provides functions for converting colors from one representation to the other description adapted from https en wikipedia orgwikirgbcolormodel and https en wikipedia orgwikihslandhsv conversion from the hsvrepresentation to the rgbrepresentation expected rgbvalues taken from https www rapidtables comconvertcolorhsvtorgb html hsvtorgb0 0 0 0 0 0 hsvtorgb0 0 1 255 255 255 hsvtorgb0 1 1 255 0 0 hsvtorgb60 1 1 255 255 0 hsvtorgb120 1 1 0 255 0 hsvtorgb240 1 1 0 0 255 hsvtorgb300 1 1 255 0 255 hsvtorgb180 0 5 0 5 64 128 128 hsvtorgb234 0 14 0 88 193 196 224 hsvtorgb330 0 75 0 5 128 32 80 conversion from the rgbrepresentation to the hsvrepresentation the tested values are the reverse values from the hsvtorgbdoctests function approximatelyequalhsv is needed because of small deviations due to rounding for the rgbvalues approximatelyequalhsvrgbtohsv0 0 0 0 0 0 true approximatelyequalhsvrgbtohsv255 255 255 0 0 1 true approximatelyequalhsvrgbtohsv255 0 0 0 1 1 true approximatelyequalhsvrgbtohsv255 255 0 60 1 1 true approximatelyequalhsvrgbtohsv0 255 0 120 1 1 true approximatelyequalhsvrgbtohsv0 0 255 240 1 1 true approximatelyequalhsvrgbtohsv255 0 255 300 1 1 true approximatelyequalhsvrgbtohsv64 128 128 180 0 5 0 5 true approximatelyequalhsvrgbtohsv193 196 224 234 0 14 0 88 true approximatelyequalhsvrgbtohsv128 32 80 330 0 75 0 5 true utilityfunction to check that two hsvcolors are approximately equal approximatelyequalhsv0 0 0 0 0 0 true approximatelyequalhsv180 0 5 0 3 179 9999 0 500001 0 30001 true approximatelyequalhsv0 0 0 1 0 0 false approximatelyequalhsv180 0 5 0 3 179 9999 0 6 0 30001 false conversion from the hsv representation to the rgb representation expected rgb values taken from https www rapidtables com convert color hsv to rgb html hsv_to_rgb 0 0 0 0 0 0 hsv_to_rgb 0 0 1 255 255 255 hsv_to_rgb 0 1 1 255 0 0 hsv_to_rgb 60 1 1 255 255 0 hsv_to_rgb 120 1 1 0 255 0 hsv_to_rgb 240 1 1 0 0 255 hsv_to_rgb 300 1 1 255 0 255 hsv_to_rgb 180 0 5 0 5 64 128 128 hsv_to_rgb 234 0 14 0 88 193 196 224 hsv_to_rgb 330 0 75 0 5 128 32 80 conversion from the rgb representation to the hsv representation the tested values are the reverse values from the hsv_to_rgb doctests function approximately_equal_hsv is needed because of small deviations due to rounding for the rgb values approximately_equal_hsv rgb_to_hsv 0 0 0 0 0 0 true approximately_equal_hsv rgb_to_hsv 255 255 255 0 0 1 true approximately_equal_hsv rgb_to_hsv 255 0 0 0 1 1 true approximately_equal_hsv rgb_to_hsv 255 255 0 60 1 1 true approximately_equal_hsv rgb_to_hsv 0 255 0 120 1 1 true approximately_equal_hsv rgb_to_hsv 0 0 255 240 1 1 true approximately_equal_hsv rgb_to_hsv 255 0 255 300 1 1 true approximately_equal_hsv rgb_to_hsv 64 128 128 180 0 5 0 5 true approximately_equal_hsv rgb_to_hsv 193 196 224 234 0 14 0 88 true approximately_equal_hsv rgb_to_hsv 128 32 80 330 0 75 0 5 true utility function to check that two hsv colors are approximately equal approximately_equal_hsv 0 0 0 0 0 0 true approximately_equal_hsv 180 0 5 0 3 179 9999 0 500001 0 30001 true approximately_equal_hsv 0 0 0 1 0 0 false approximately_equal_hsv 180 0 5 0 3 179 9999 0 6 0 30001 false
def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]: if hue < 0 or hue > 360: raise Exception("hue should be between 0 and 360") if saturation < 0 or saturation > 1: raise Exception("saturation should be between 0 and 1") if value < 0 or value > 1: raise Exception("value should be between 0 and 1") chroma = value * saturation hue_section = hue / 60 second_largest_component = chroma * (1 - abs(hue_section % 2 - 1)) match_value = value - chroma if hue_section >= 0 and hue_section <= 1: red = round(255 * (chroma + match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (match_value)) elif hue_section > 1 and hue_section <= 2: red = round(255 * (second_largest_component + match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (match_value)) elif hue_section > 2 and hue_section <= 3: red = round(255 * (match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (second_largest_component + match_value)) elif hue_section > 3 and hue_section <= 4: red = round(255 * (match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (chroma + match_value)) elif hue_section > 4 and hue_section <= 5: red = round(255 * (second_largest_component + match_value)) green = round(255 * (match_value)) blue = round(255 * (chroma + match_value)) else: red = round(255 * (chroma + match_value)) green = round(255 * (match_value)) blue = round(255 * (second_largest_component + match_value)) return [red, green, blue] def rgb_to_hsv(red: int, green: int, blue: int) -> list[float]: if red < 0 or red > 255: raise Exception("red should be between 0 and 255") if green < 0 or green > 255: raise Exception("green should be between 0 and 255") if blue < 0 or blue > 255: raise Exception("blue should be between 0 and 255") float_red = red / 255 float_green = green / 255 float_blue = blue / 255 value = max(float_red, float_green, float_blue) chroma = value - min(float_red, float_green, float_blue) saturation = 0 if value == 0 else chroma / value if chroma == 0: hue = 0.0 elif value == float_red: hue = 60 * (0 + (float_green - float_blue) / chroma) elif value == float_green: hue = 60 * (2 + (float_blue - float_red) / chroma) else: hue = 60 * (4 + (float_red - float_green) / chroma) hue = (hue + 360) % 360 return [hue, saturation, value] def approximately_equal_hsv(hsv_1: list[float], hsv_2: list[float]) -> bool: check_hue = abs(hsv_1[0] - hsv_2[0]) < 0.2 check_saturation = abs(hsv_1[1] - hsv_2[1]) < 0.002 check_value = abs(hsv_1[2] - hsv_2[2]) < 0.002 return check_hue and check_saturation and check_value
leetcode no 13 roman to integer given a roman numeral convert it to an integer input is guaranteed to be within the range from 1 to 3999 https en wikipedia orgwikiromannumerals tests iii 3 cliv 154 mix 1009 mmd 2500 mmmcmxcix 3999 allromantointkey value for key value in tests items true given a integer convert it to an roman numeral https en wikipedia orgwikiromannumerals tests iii 3 cliv 154 mix 1009 mmd 2500 mmmcmxcix 3999 allinttoromanvalue key for key value in tests items true leetcode no 13 roman to integer given a roman numeral convert it to an integer input is guaranteed to be within the range from 1 to 3999 https en wikipedia org wiki roman_numerals tests iii 3 cliv 154 mix 1009 mmd 2500 mmmcmxcix 3999 all roman_to_int key value for key value in tests items true given a integer convert it to an roman numeral https en wikipedia org wiki roman_numerals tests iii 3 cliv 154 mix 1009 mmd 2500 mmmcmxcix 3999 all int_to_roman value key for key value in tests items true
ROMAN = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def roman_to_int(roman: str) -> int: vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} total = 0 place = 0 while place < len(roman): if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def int_to_roman(number: int) -> str: result = [] for arabic, roman in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: break return "".join(result) if __name__ == "__main__": import doctest doctest.testmod()
convert speed units https en wikipedia orgwikikilometresperhour https en wikipedia orgwikimilesperhour https en wikipedia orgwikiknotunit https en wikipedia orgwikimetrepersecond convert speed from one unit to another using the speedchart above kmh 1 0 ms 3 6 mph 1 609344 knot 1 852 convertspeed100 kmh ms 27 778 convertspeed100 kmh mph 62 137 convertspeed100 kmh knot 53 996 convertspeed100 ms kmh 360 0 convertspeed100 ms mph 223 694 convertspeed100 ms knot 194 384 convertspeed100 mph kmh 160 934 convertspeed100 mph ms 44 704 convertspeed100 mph knot 86 898 convertspeed100 knot kmh 185 2 convertspeed100 knot ms 51 444 convertspeed100 knot mph 115 078 convert speed from one unit to another using the speed_chart above km h 1 0 m s 3 6 mph 1 609344 knot 1 852 convert_speed 100 km h m s 27 778 convert_speed 100 km h mph 62 137 convert_speed 100 km h knot 53 996 convert_speed 100 m s km h 360 0 convert_speed 100 m s mph 223 694 convert_speed 100 m s knot 194 384 convert_speed 100 mph km h 160 934 convert_speed 100 mph m s 44 704 convert_speed 100 mph knot 86 898 convert_speed 100 knot km h 185 2 convert_speed 100 knot m s 51 444 convert_speed 100 knot mph 115 078
speed_chart: dict[str, float] = { "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, } speed_chart_inverse: dict[str, float] = { "km/h": 1.0, "m/s": 0.277777778, "mph": 0.621371192, "knot": 0.539956803, } def convert_speed(speed: float, unit_from: str, unit_to: str) -> float: if unit_to not in speed_chart or unit_from not in speed_chart_inverse: msg = ( f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n" f"Valid values are: {', '.join(speed_chart_inverse)}" ) raise ValueError(msg) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3) if __name__ == "__main__": import doctest doctest.testmod()
convert between different units of temperature def celsiustofahrenheitcelsius float ndigits int 2 float return roundfloatcelsius 9 5 32 ndigits def celsiustokelvincelsius float ndigits int 2 float return roundfloatcelsius 273 15 ndigits def celsiustorankinecelsius float ndigits int 2 float return roundfloatcelsius 9 5 491 67 ndigits def fahrenheittocelsiusfahrenheit float ndigits int 2 float return roundfloatfahrenheit 32 5 9 ndigits def fahrenheittokelvinfahrenheit float ndigits int 2 float return roundfloatfahrenheit 32 5 9 273 15 ndigits def fahrenheittorankinefahrenheit float ndigits int 2 float return roundfloatfahrenheit 459 67 ndigits def kelvintocelsiuskelvin float ndigits int 2 float return roundfloatkelvin 273 15 ndigits def kelvintofahrenheitkelvin float ndigits int 2 float return roundfloatkelvin 273 15 9 5 32 ndigits def kelvintorankinekelvin float ndigits int 2 float return roundfloatkelvin 9 5 ndigits def rankinetocelsiusrankine float ndigits int 2 float return roundfloatrankine 491 67 5 9 ndigits def rankinetofahrenheitrankine float ndigits int 2 float return roundfloatrankine 459 67 ndigits def rankinetokelvinrankine float ndigits int 2 float return roundfloatrankine 5 9 ndigits def reaumurtokelvinreaumur float ndigits int 2 float return roundfloatreaumur 1 25 273 15 ndigits def reaumurtofahrenheitreaumur float ndigits int 2 float return roundfloatreaumur 2 25 32 ndigits def reaumurtocelsiusreaumur float ndigits int 2 float return roundfloatreaumur 1 25 ndigits def reaumurtorankinereaumur float ndigits int 2 float return roundfloatreaumur 2 25 32 459 67 ndigits if name main import doctest doctest testmod convert a given value from celsius to fahrenheit and round it to 2 decimal places wikipedia reference https en wikipedia org wiki celsius wikipedia reference https en wikipedia org wiki fahrenheit celsius_to_fahrenheit 273 354 3 524 037 celsius_to_fahrenheit 273 354 0 524 0 celsius_to_fahrenheit 40 0 40 0 celsius_to_fahrenheit 20 0 4 0 celsius_to_fahrenheit 0 32 0 celsius_to_fahrenheit 20 68 0 celsius_to_fahrenheit 40 104 0 celsius_to_fahrenheit celsius traceback most recent call last valueerror could not convert string to float celsius convert a given value from celsius to kelvin and round it to 2 decimal places wikipedia reference https en wikipedia org wiki celsius wikipedia reference https en wikipedia org wiki kelvin celsius_to_kelvin 273 354 3 546 504 celsius_to_kelvin 273 354 0 547 0 celsius_to_kelvin 0 273 15 celsius_to_kelvin 20 0 293 15 celsius_to_kelvin 40 313 15 celsius_to_kelvin celsius traceback most recent call last valueerror could not convert string to float celsius convert a given value from celsius to rankine and round it to 2 decimal places wikipedia reference https en wikipedia org wiki celsius wikipedia reference https en wikipedia org wiki rankine_scale celsius_to_rankine 273 354 3 983 707 celsius_to_rankine 273 354 0 984 0 celsius_to_rankine 0 491 67 celsius_to_rankine 20 0 527 67 celsius_to_rankine 40 563 67 celsius_to_rankine celsius traceback most recent call last valueerror could not convert string to float celsius convert a given value from fahrenheit to celsius and round it to 2 decimal places wikipedia reference https en wikipedia org wiki fahrenheit wikipedia reference https en wikipedia org wiki celsius fahrenheit_to_celsius 273 354 3 134 086 fahrenheit_to_celsius 273 354 0 134 0 fahrenheit_to_celsius 0 17 78 fahrenheit_to_celsius 20 0 6 67 fahrenheit_to_celsius 40 0 4 44 fahrenheit_to_celsius 60 15 56 fahrenheit_to_celsius 80 26 67 fahrenheit_to_celsius 100 37 78 fahrenheit_to_celsius fahrenheit traceback most recent call last valueerror could not convert string to float fahrenheit convert a given value from fahrenheit to kelvin and round it to 2 decimal places wikipedia reference https en wikipedia org wiki fahrenheit wikipedia reference https en wikipedia org wiki kelvin fahrenheit_to_kelvin 273 354 3 407 236 fahrenheit_to_kelvin 273 354 0 407 0 fahrenheit_to_kelvin 0 255 37 fahrenheit_to_kelvin 20 0 266 48 fahrenheit_to_kelvin 40 0 277 59 fahrenheit_to_kelvin 60 288 71 fahrenheit_to_kelvin 80 299 82 fahrenheit_to_kelvin 100 310 93 fahrenheit_to_kelvin fahrenheit traceback most recent call last valueerror could not convert string to float fahrenheit convert a given value from fahrenheit to rankine and round it to 2 decimal places wikipedia reference https en wikipedia org wiki fahrenheit wikipedia reference https en wikipedia org wiki rankine_scale fahrenheit_to_rankine 273 354 3 733 024 fahrenheit_to_rankine 273 354 0 733 0 fahrenheit_to_rankine 0 459 67 fahrenheit_to_rankine 20 0 479 67 fahrenheit_to_rankine 40 0 499 67 fahrenheit_to_rankine 60 519 67 fahrenheit_to_rankine 80 539 67 fahrenheit_to_rankine 100 559 67 fahrenheit_to_rankine fahrenheit traceback most recent call last valueerror could not convert string to float fahrenheit convert a given value from kelvin to celsius and round it to 2 decimal places wikipedia reference https en wikipedia org wiki kelvin wikipedia reference https en wikipedia org wiki celsius kelvin_to_celsius 273 354 3 0 204 kelvin_to_celsius 273 354 0 0 0 kelvin_to_celsius 273 15 0 0 kelvin_to_celsius 300 26 85 kelvin_to_celsius 315 5 42 35 kelvin_to_celsius kelvin traceback most recent call last valueerror could not convert string to float kelvin convert a given value from kelvin to fahrenheit and round it to 2 decimal places wikipedia reference https en wikipedia org wiki kelvin wikipedia reference https en wikipedia org wiki fahrenheit kelvin_to_fahrenheit 273 354 3 32 367 kelvin_to_fahrenheit 273 354 0 32 0 kelvin_to_fahrenheit 273 15 32 0 kelvin_to_fahrenheit 300 80 33 kelvin_to_fahrenheit 315 5 108 23 kelvin_to_fahrenheit kelvin traceback most recent call last valueerror could not convert string to float kelvin convert a given value from kelvin to rankine and round it to 2 decimal places wikipedia reference https en wikipedia org wiki kelvin wikipedia reference https en wikipedia org wiki rankine_scale kelvin_to_rankine 273 354 3 492 037 kelvin_to_rankine 273 354 0 492 0 kelvin_to_rankine 0 0 0 kelvin_to_rankine 20 0 36 0 kelvin_to_rankine 40 72 0 kelvin_to_rankine kelvin traceback most recent call last valueerror could not convert string to float kelvin convert a given value from rankine to celsius and round it to 2 decimal places wikipedia reference https en wikipedia org wiki rankine_scale wikipedia reference https en wikipedia org wiki celsius rankine_to_celsius 273 354 3 121 287 rankine_to_celsius 273 354 0 121 0 rankine_to_celsius 273 15 121 4 rankine_to_celsius 300 106 48 rankine_to_celsius 315 5 97 87 rankine_to_celsius rankine traceback most recent call last valueerror could not convert string to float rankine convert a given value from rankine to fahrenheit and round it to 2 decimal places wikipedia reference https en wikipedia org wiki rankine_scale wikipedia reference https en wikipedia org wiki fahrenheit rankine_to_fahrenheit 273 15 186 52 rankine_to_fahrenheit 300 159 67 rankine_to_fahrenheit 315 5 144 17 rankine_to_fahrenheit rankine traceback most recent call last valueerror could not convert string to float rankine convert a given value from rankine to kelvin and round it to 2 decimal places wikipedia reference https en wikipedia org wiki rankine_scale wikipedia reference https en wikipedia org wiki kelvin rankine_to_kelvin 0 0 0 rankine_to_kelvin 20 0 11 11 rankine_to_kelvin 40 22 22 rankine_to_kelvin rankine traceback most recent call last valueerror could not convert string to float rankine convert a given value from reaumur to kelvin and round it to 2 decimal places reference http www csgnetwork com temp2conv html reaumur_to_kelvin 0 273 15 reaumur_to_kelvin 20 0 298 15 reaumur_to_kelvin 40 323 15 reaumur_to_kelvin reaumur traceback most recent call last valueerror could not convert string to float reaumur convert a given value from reaumur to fahrenheit and round it to 2 decimal places reference http www csgnetwork com temp2conv html reaumur_to_fahrenheit 0 32 0 reaumur_to_fahrenheit 20 0 77 0 reaumur_to_fahrenheit 40 122 0 reaumur_to_fahrenheit reaumur traceback most recent call last valueerror could not convert string to float reaumur convert a given value from reaumur to celsius and round it to 2 decimal places reference http www csgnetwork com temp2conv html reaumur_to_celsius 0 0 0 reaumur_to_celsius 20 0 25 0 reaumur_to_celsius 40 50 0 reaumur_to_celsius reaumur traceback most recent call last valueerror could not convert string to float reaumur convert a given value from reaumur to rankine and round it to 2 decimal places reference http www csgnetwork com temp2conv html reaumur_to_rankine 0 491 67 reaumur_to_rankine 20 0 536 67 reaumur_to_rankine 40 581 67 reaumur_to_rankine reaumur traceback most recent call last valueerror could not convert string to float reaumur
def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: return round((float(celsius) * 9 / 5) + 32, ndigits) def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: return round(float(celsius) + 273.15, ndigits) def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest doctest.testmod()
a unit of time is any particular time interval used as a standard way of measuring or expressing duration the base unit of time in the international system of units si and by extension most of the western world is the second defined as about 9 billion oscillations of the caesium atom https en wikipedia orgwikiunitoftime convert time from one unit to another using the timechart above converttime3600 seconds hours 1 0 converttime3500 seconds hours 0 972 converttime1 days hours 24 0 converttime120 minutes seconds 7200 0 converttime2 weeks days 14 0 converttime0 5 hours minutes 30 0 converttime3600 seconds hours traceback most recent call last valueerror timevalue must be a nonnegative number converttimehello hours minutes traceback most recent call last valueerror timevalue must be a nonnegative number converttime0 1 2 weeks days traceback most recent call last valueerror timevalue must be a nonnegative number converttime1 cool century doctest ellipsis traceback most recent call last valueerror invalid unit cool is not in seconds minutes hours days weeks converttime1 seconds hot doctest ellipsis traceback most recent call last valueerror invalid unit hot is not in seconds minutes hours days weeks 1 minute 60 sec 1 hour 60 minutes 3600 seconds 1 day 24 hours 1440 min 86400 sec 1 week 7d 168hr 10080min 604800 sec approximate value for a month in seconds approximate value for a year in seconds convert time from one unit to another using the time_chart above convert_time 3600 seconds hours 1 0 convert_time 3500 seconds hours 0 972 convert_time 1 days hours 24 0 convert_time 120 minutes seconds 7200 0 convert_time 2 weeks days 14 0 convert_time 0 5 hours minutes 30 0 convert_time 3600 seconds hours traceback most recent call last valueerror time_value must be a non negative number convert_time hello hours minutes traceback most recent call last valueerror time_value must be a non negative number convert_time 0 1 2 weeks days traceback most recent call last valueerror time_value must be a non negative number convert_time 1 cool century doctest ellipsis traceback most recent call last valueerror invalid unit cool is not in seconds minutes hours days weeks convert_time 1 seconds hot doctest ellipsis traceback most recent call last valueerror invalid unit hot is not in seconds minutes hours days weeks
time_chart: dict[str, float] = { "seconds": 1.0, "minutes": 60.0, "hours": 3600.0, "days": 86400.0, "weeks": 604800.0, "months": 2629800.0, "years": 31557600.0, } time_chart_inverse: dict[str, float] = { key: 1 / value for key, value in time_chart.items() } def convert_time(time_value: float, unit_from: str, unit_to: str) -> float: if not isinstance(time_value, (int, float)) or time_value < 0: msg = "'time_value' must be a non-negative number." raise ValueError(msg) unit_from = unit_from.lower() unit_to = unit_to.lower() if unit_from not in time_chart or unit_to not in time_chart: invalid_unit = unit_from if unit_from not in time_chart else unit_to msg = f"Invalid unit {invalid_unit} is not in {', '.join(time_chart)}." raise ValueError(msg) return round( time_value * time_chart[unit_from] * time_chart_inverse[unit_to], 3, ) if __name__ == "__main__": import doctest doctest.testmod() print(f"{convert_time(3600,'seconds', 'hours') = :,}") print(f"{convert_time(360, 'days', 'months') = :,}") print(f"{convert_time(360, 'months', 'years') = :,}") print(f"{convert_time(1, 'years', 'seconds') = :,}")