Prompt stringlengths 16 11.5k | Completions stringlengths 84 25.3k |
|---|---|
Author : Alexander Pantyukhin Date : November 1, 2022 Task: Given a positive int number. Return True if this number is power of 2 or False otherwise. Implementation notes: Use bit manipulation. For example if the number is the power of two it's bits representation: n 0..100..00 n 1 0..011..11 n n 1 no int... | def is_power_of_two(number: int) -> bool:
"""
Return True if this number is power of 2 or False otherwise.
>>> is_power_of_two(0)
True
>>> is_power_of_two(1)
True
>>> is_power_of_two(2)
True
>>> is_power_of_two(4)
True
>>> is_power_of_two(6)
False
>>> is_power_of_two... |
Author : Naman Sharma Date : October 2, 2023 Task: To Find the largest power of 2 less than or equal to a given number. Implementation notes: Use bit manipulation. We start from 1 left shift the set bit to check if res1number. Each left bit shift represents a pow of 2. For example: number: 15 res: 1 0b1 2 0... | def largest_pow_of_two_le_num(number: int) -> int:
"""
Return the largest power of two less than or equal to a number.
>>> largest_pow_of_two_le_num(0)
0
>>> largest_pow_of_two_le_num(1)
1
>>> largest_pow_of_two_le_num(-1)
0
>>> largest_pow_of_two_le_num(3)
2
>>> largest_pow... |
Finds the missing number in a list of consecutive integers. Args: nums: A list of integers. Returns: The missing number. Example: findmissingnumber0, 1, 3, 4 2 findmissingnumber4, 3, 1, 0 2 findmissingnumber4, 3, 1, 0 2 findmissingnumber2, 2, 1, 3, 0 1 findmissingnumber1, 3, 4, 5, 6 2 findmissingnumber6, 5, 4, 2,... | def find_missing_number(nums: list[int]) -> int:
"""
Finds the missing number in a list of consecutive integers.
Args:
nums: A list of integers.
Returns:
The missing number.
Example:
>>> find_missing_number([0, 1, 3, 4])
2
>>> find_missing_number([4, 3, 1, ... |
Author : Alexander Pantyukhin Date : November 30, 2022 Task: Given two int numbers. Return True these numbers have opposite signs or False otherwise. Implementation notes: Use bit manipulation. Use XOR for two numbers. Return True if numbers have opposite signs False otherwise. differentsigns1, 1 True differentsi... | def different_signs(num1: int, num2: int) -> bool:
"""
Return True if numbers have opposite signs False otherwise.
>>> different_signs(1, -1)
True
>>> different_signs(1, 1)
False
>>> different_signs(1000000000000000000000000000, -1000000000000000000000000000)
True
>>> different_sign... |
Task: Given a positive int number. Return True if this number is power of 4 or False otherwise. Implementation notes: Use bit manipulation. For example if the number is the power of 2 it's bits representation: n 0..100..00 n 1 0..011..11 n n 1 no intersections 0 If the number is a power of 4 then it should b... | def power_of_4(number: int) -> bool:
"""
Return True if this number is power of 4 or False otherwise.
>>> power_of_4(0)
Traceback (most recent call last):
...
ValueError: number must be positive
>>> power_of_4(1)
True
>>> power_of_4(2)
False
>>> power_of_4(4)
True
... |
return the bit string of an integer getreversebitstring9 '10010000000000000000000000000000' getreversebitstring43 '11010100000000000000000000000000' getreversebitstring2873 '10011100110100000000000000000000' getreversebitstringthis is not a number Traceback most recent call last: ... TypeError: operation can not be... | def get_reverse_bit_string(number: int) -> str:
"""
return the bit string of an integer
>>> get_reverse_bit_string(9)
'10010000000000000000000000000000'
>>> get_reverse_bit_string(43)
'11010100000000000000000000000000'
>>> get_reverse_bit_string(2873)
'10011100110100000000000000000000'
... |
!usrbinenv python3 Provide the functionality to manipulate a single bit. def setbitnumber: int, position: int int: return number 1 position def clearbitnumber: int, position: int int: return number 1 position def flipbitnumber: int, position: int int: return number 1 position def isbitsetnumber: int, position:... | #!/usr/bin/env python3
"""Provide the functionality to manipulate a single bit."""
def set_bit(number: int, position: int) -> int:
"""
Set the bit at position to 1.
Details: perform bitwise or for given number and X.
Where X is a number with all the bits – zeroes and bit on given
position – one.... |
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 sw... | def show_bits(before: int, after: int) -> str:
"""
>>> print(show_bits(0, 0xFFFF))
0: 00000000
65535: 1111111111111111
"""
return f"{before:>5}: {before:08b}\n{after:>5}: {after:08b}"
def swap_odd_even_bits(num: int) -> int:
"""
1. We use bitwise AND operations to separate the even... |
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 a... | from __future__ import annotations
from maths.greatest_common_divisor import greatest_common_divisor
def diophantine(a: int, b: int, c: int) -> tuple[float, float]:
"""
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 (wher... |
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.... | def and_gate(input_1: int, input_2: int) -> int:
"""
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
"""
return int(input_1 and input_2)
if __name__ == "__main__":
import doctest
doctest.tes... |
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... | def imply_gate(input_1: int, input_2: int) -> int:
"""
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
"""
return int(input_1 == 0 or input_2 == 1)
if __name__ == "__main__":
import doc... |
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 si... | def simplify_kmap(kmap: list[list[int]]) -> str:
"""
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]])
... |
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.comsolvedproblemso... | def mux(input0: int, input1: int, select: int) -> int:
"""
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 t... |
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... | def nand_gate(input_1: int, input_2: int) -> int:
"""
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
"""
return int(not (input_1 and input_2))
if __name__ == "__main__":
import doctest
... |
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... | def nimply_gate(input_1: int, input_2: int) -> int:
"""
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
"""
return int(input_1 == 1 and input_2 == 0)
if __name__ == "__main__":
imp... |
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 ... | from collections.abc import Callable
def nor_gate(input_1: int, input_2: int) -> int:
"""
>>> 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
"""
return int(input_1 == input_2 == ... |
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 not... | def not_gate(input_1: int) -> int:
"""
Calculate NOT of the input values
>>> not_gate(0)
1
>>> not_gate(1)
0
"""
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.g... | def or_gate(input_1: int, input_2: int) -> int:
"""
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
"""
return int((input_1, input_2).count(1) != 0)
if __name__ == "__main__":
import doctest
docte... |
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 | from __future__ import annotations
from collections.abc import Sequence
from typing import Literal
def compare_string(string1: str, string2: str) -> str | Literal[False]:
"""
>>> compare_string('0010','0110')
'0_10'
>>> compare_string('0110','1101')
False
"""
list1 = list(string1)
li... |
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 ... | def xnor_gate(input_1: int, input_2: int) -> int:
"""
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
"""
return 1 if input_1 == input_2 else 0
if __name__ == "__main__":
import doctest
d... |
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 ... | def xor_gate(input_1: int, input_2: int) -> int:
"""
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
"""
return (input_1, input_2).count(0) % 2
if __name__ == "__main__":
import doctest
doct... |
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 ex... | from __future__ import annotations
from PIL import Image
# Define glider example
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,... |
Conway's Game Of Life, Author 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... | 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 f... |
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 Ini... | from functools import partial
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
WIDTH = 80
HEIGHT = 80
class LangtonsAnt:
"""
Represents the main LangonsAnt algorithm.
>>> la = LangtonsAnt(2, 2)
>>> la.board
[[True, True], [True, True]]
>>> la.ant_position
... |
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 t... | 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:
"""
Build the highway following the parameters given
>>> construct_highway(... |
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... | from __future__ import annotations
from PIL import Image
# Define the first generation of cells
# fmt: off
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]]
# fmt: on
def format_ruleset(ruleset: int) -> list[int]:
"""
>>> format_ruleset(11100)
... |
WaTor algorithm 1984 https:en.wikipedia.orgwikiWaTor https:beltoforion.deenwator https:beltoforion.deenwatorimageswatormedium.webm This solution aims to completely remove any systematic approach to the WaTor planet, and utilise fully random methods. The constants are a working set that allows the WaTor planet to res... | from collections.abc import Callable
from random import randint, shuffle
from time import sleep
from typing import Literal
WIDTH = 50 # Width of the Wa-Tor planet
HEIGHT = 50 # Height of the Wa-Tor planet
PREY_INITIAL_COUNT = 30 # The initial number of prey entities
PREY_REPRODUCTION_TIME = 5 # The chronons befor... |
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' | from __future__ import annotations
def encode(plain: str) -> list[int]:
"""
>>> encode("myname")
[13, 25, 14, 1, 13, 5]
"""
return [ord(elem) - 96 for elem in plain]
def decode(encoded: list[int]) -> str:
"""
>>> decode([13, 25, 14, 1, 13, 5])
'myname'
"""
return "".join(chr(... |
encryptmessage4545, 'The affine cipher is a type of monoalphabetic ' ... 'substitution cipher.' 'VLp MMIpHLGpvp pFsHpxMpyxIx JHL OFpvuOvFFuFxIpHLGi' decryptmessage4545, 'VLp MMIpHLGpvp pFsHpxMpyxIx JHL OFpvuOvFFuF' ... 'xIpHLGi' 'The affine cipher is a type of monoalphabetic... | import random
import sys
from maths.greatest_common_divisor import gcd_by_iterative
from . import cryptomath_module as cryptomath
SYMBOLS = (
r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`"""
r"""abcdefghijklmnopqrstuvwxyz{|}~"""
)
def check_keys(key_a: int, key_b: int, mode: str) ->... |
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 ... | import string
def atbash_slow(sequence: str) -> str:
"""
>>> atbash_slow("ABCDEFG")
'ZYXWVUT'
>>> atbash_slow("aW;;123BX")
'zD;;123YC'
"""
output = ""
for i in sequence:
extract = ord(i)
if 65 <= extract <= 90:
output += chr(155 - extract)
elif 97 <... |
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 pr... | def encrypt(plaintext: str, key: str) -> str:
"""
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("c... |
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: ... Exc... | 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"... |
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,... | def base16_encode(data: bytes) -> str:
"""
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 (wher... |
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' ... | B32_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
def base32_encode(data: bytes) -> bytes:
"""
>>> base32_encode(b"Hello World!")
b'JBSWY3DPEBLW64TMMQQQ===='
>>> base32_encode(b"123456")
b'GEZDGNBVGY======'
>>> base32_encode(b"some long complex string")
b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJU... |
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, th... | B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def base64_encode(data: bytes) -> bytes:
"""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 wil... |
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' | 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:
"""
>>> ascii85_encode(b"")
b''
>... |
Author: 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 ... | from string import ascii_uppercase
dict1 = {char: i for i, char in enumerate(ascii_uppercase)}
dict2 = dict(enumerate(ascii_uppercase))
# This function generates the key in
# a cyclic manner until it's length isn't
# equal to the length of original text
def generate_key(message: str, key: str) -> str:
"""
>>... |
!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.l... | #!/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
"""
import numpy as np
SQUARE = [
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"... |
decrypt'TMDETUX PMDVU' Decryption using Key 0: TMDETUX PMDVU Decryption using Key 1: SLCDSTW OLCUT Decryption using Key 2: RKBCRSV NKBTS Decryption using Key 3: QJABQRU MJASR Decryption using Key 4: PIZAPQT LIZRQ Decryption using Key 5: OHYZOPS KHYQP Decryption using Key 6: NGXYNOR JGXPO Decryption using Key 7: MFWXMNQ... | import string
def decrypt(message: str) -> None:
"""
>>> decrypt('TMDETUX PMDVU')
Decryption using Key #0: TMDETUX PMDVU
Decryption using Key #1: SLCDSTW OLCUT
Decryption using Key #2: RKBCRSV NKBTS
Decryption using Key #3: QJABQRU MJASR
Decryption using Key #4: PIZAPQT LIZRQ
Decryptio... |
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 alph... | from __future__ import annotations
from string import ascii_letters
def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
"""
encrypt
=======
Encodes a given string with the caesar cipher and returns the encoded
message
Parameters:
-----------
* input_string... |
!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 valu... | #!/usr/bin/env python3
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]:
"""
Basic Usage
===========... |
Created by 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... | def miller_rabin(n: int, allow_probable: bool = False) -> bool:
"""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 va... |
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 ... | from __future__ import annotations
def find_primitive(modulus: int) -> int | None:
"""
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.
Exampl... |
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 ... | from binascii import hexlify
from hashlib import sha256
from os import urandom
# RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for
# Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526
primes = {
# 1536-bit
5: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234... |
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! | import os
import random
import sys
from . import cryptomath_module as cryptomath
from . import rabin_miller
min_primitive_root = 3
# 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 Cry... |
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 ... | from __future__ import annotations
RotorPositionT = tuple[int, int, int]
RotorSelectionT = tuple[str, str, str]
# used alphabet --------------------------
# from string.ascii_uppercase
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# -------------------------- default selection --------------------------
# rotors -------------... |
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:p... | import string
MORSE_CODE_DICT = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".... |
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 t... | import string
import numpy
from maths.greatest_common_divisor import greatest_common_divisor
class HillCipher:
key_string = string.ascii_uppercase + string.digits
# This cipher takes alphanumerics into account
# i.e. a total of 36 characters
# take x and return x % len(key_string)
modulus = num... |
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', ... | from string import ascii_uppercase
def mixed_keyword(
keyword: str, plaintext: str, verbose: bool = False, alphabet: str = ascii_uppercase
) -> str:
"""
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("colleg... |
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' | from typing import Literal
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def translate_message(
key: str, message: str, mode: Literal["encrypt", "decrypt"]
) -> str:
"""
>>> translate_message("QWERTYUIOPASDFGHJKLZXCVBNM","Hello World","encrypt")
'Pcssi Bidsm'
"""
chars_a = LETTERS if mode == "decryp... |
!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
MORSE_CODE_DICT = {
"A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.",
"H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--... |
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 Onepa... | import random
class Onepad:
@staticmethod
def encrypt(text: str) -> tuple[list[int], list[int]]:
"""
Function to encrypt text using pseudo-random numbers
>>> Onepad().encrypt("")
([], [])
>>> Onepad().encrypt([])
([], [])
>>> random.seed(1)
>>> O... |
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 integer... | import random
def generate_valid_block_size(message_length: int) -> int:
"""
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)
>... |
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 techniq... | 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 p... |
!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.arrayequalPolybiusCi... | #!/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
"""
import numpy as np
SQUARE = [
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
["q", "r", "s", "... |
generatetable'marvin' doctest: NORMALIZEWHITESPACE 'ABCDEFGHIJKLM', 'UVWXYZNOPQRST', 'ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ', 'ABCDEFGHIJKLM', 'STUVWXYZNOPQR', 'ABCDEFGHIJKLM', 'QRSTUVWXYZNOP', 'ABCDEFGHIJKLM', 'WXYZNOPQRSTUV', 'ABCDEFGHIJKLM', 'UVWXYZNOPQRST' encrypt'marvin', 'jessica' 'QRACRWU' decrypt'marvin', 'QRACRWU... | alphabet = {
"A": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"),
"B": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"),
"C": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"),
"D": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"),
"E": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"),
"F": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"),
"G": ("ABCDEFGHIJKLM", "XYZNOPQRS... |
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
... |
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 posit... | def encrypt(input_string: str, key: int) -> str:
"""
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)... |
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 | def dencrypt(s: str, n: int = 13) -> str:
"""
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
... |
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 inc... | from __future__ import annotations
import math
import random
def rsafactor(d: int, e: int, n: int) -> list[int]:
"""
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 pu... |
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 | 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[tu... |
https:en.wikipedia.orgwikiRunningkeycipher Encrypts the plaintext using the Running Key Cipher. :param key: The running key long piece of text. :param plaintext: The plaintext to be encrypted. :return: The ciphertext. Decrypts the ciphertext using the Running Key Cipher. :param key: The running key long piece of text. ... | def running_key_encrypt(key: str, plaintext: str) -> str:
"""
Encrypts the plaintext using the Running Key Cipher.
:param key: The running key (long piece of text).
:param plaintext: The plaintext to be encrypted.
:return: The ciphertext.
"""
plaintext = plaintext.replace(" ", "").upper()
... |
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 th... | from __future__ import annotations
import random
import string
class ShuffledShiftCipher:
"""
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 t... |
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 ... | def remove_duplicates(key: str) -> str:
"""
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'
"""
key_no_dups =... |
encryptmessage'LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji' 'Ilcrism Olcvs' decryptmessage'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 = e... |
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. Ap... | import math
"""
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 t... |
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 'm... | from __future__ import annotations
# fmt: off
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":... |
vernamencryptHELLO,KEY 'RIJVS' vernamdecryptRIJVS,KEY 'HELLO' Example usage | def vernam_encrypt(plaintext: str, key: str) -> str:
"""
>>> vernam_encrypt("HELLO","KEY")
'RIJVS'
"""
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 + ... |
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.' | 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.lo... |
author: 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 : boole... | from __future__ import annotations
class XORCipher:
def __init__(self, key: int = 0):
"""
simple constructor that receives a key or uses
default key = 0
"""
# private field
self.__key = key
def encrypt(self, content: str, key: int) -> list[str]:
"""
... |
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 ... | 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]:
"""
:param s: The string that will be rotated len(s) times.
:return: A list with the rotations.
:raises TypeErr... |
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, ... | 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... |
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 a... | import math
import os
import sys
def read_file_binary(file_path: str) -> str:
"""
Reads given file as bytes and returns them as a long string
"""
result = ""
try:
with open(file_path, "rb") as binary_file:
data = binary_file.read()
for dat in data:
curr_byte... |
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 str... | import math
import sys
def read_file_binary(file_path: str) -> str:
"""
Reads given file as bytes and returns them as a long string
"""
result = ""
try:
with open(file_path, "rb") as binary_file:
data = binary_file.read()
for dat in data:
curr_byte = f"{dat:... |
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 l... | from dataclasses import dataclass
__version__ = "0.1"
__author__ = "Lucia Harcekova"
@dataclass
class Token:
"""
Dataclass representing triplet called token consisting of length, offset
and indicator. This triplet is used during LZ77 compression.
"""
offset: int
length: int
indicator: st... |
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 | 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_pat... |
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 runlengthdeco... | # https://en.wikipedia.org/wiki/Run-length_encoding
def run_length_encode(text: str) -> list:
"""
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... |
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... | import glob
import os
import random
from string import ascii_lowercase, digits
import cv2
"""
Flip image and bounding box for computer vision task
https://paperswithcode.com/method/randomhorizontalflip
"""
# Params
LABEL_DIR = ""
IMAGE_DIR = ""
OUTPUT_DIR = ""
FLIP_TYPE = 1 # (0 is vertical, 1 is horizontal)
def ... |
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.816... | import imageio.v2 as imageio
import numpy as np
def root_mean_square_error(original: np.ndarray, reference: np.ndarray) -> float:
"""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]))
... |
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 | import cv2
import numpy as np
"""
Harris Corner Detector
https://en.wikipedia.org/wiki/Harris_Corner_Detector
"""
class HarrisCorner:
def __init__(self, k: float, window_size: int):
"""
k : is an empirically determined constant in [0.04,0.06]
window_size : neighbourhoods considered
... |
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.dkimagecano... | 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:
"""
Warps the pixels of an image into a new image using the horizontal and vertical
flows.
Pixels that are wa... |
Mean thresholding algorithm for image processing https:en.wikipedia.orgwikiThresholdingimageprocessing image: is a grayscale PIL image object | from PIL import Image
"""
Mean thresholding algorithm for image processing
https://en.wikipedia.org/wiki/Thresholding_(image_processing)
"""
def mean_threshold(image: Image) -> Image:
"""
image: is a grayscale PIL image object
"""
height, width = image.size
mean = 0
pixels = image.load()
... |
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 I... | import glob
import os
import random
from string import ascii_lowercase, digits
import cv2
import numpy as np
# Parameters
OUTPUT_SIZE = (720, 1280) # Height, Width
SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it.
FILTER_TINY_SCALE = 1 / 100
LABEL_DIR = ""
IMG_DIR = ""
OUTPUT_DIR = ""
NU... |
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... | # Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling
# Importing the libraries
import numpy as np
from PIL import Image
# Maxpooling Function
def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray:
"""
This function is used to perform maxpooling on the input array of 2D ma... |
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... | UNIT_SYMBOL = {
"meter": "m",
"kilometer": "km",
"megametre": "Mm",
"gigametre": "Gm",
"terametre": "Tm",
"petametre": "Pm",
"exametre": "Em",
"zettametre": "Zm",
"yottametre": "Ym",
}
# Exponent of the factor(meter)
METRIC_CONVERSION = {
"m": 0,
"km": 3,
"Mm": 6,
"Gm... |
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 p... | def bin_to_decimal(bin_string: str) -> int:
"""
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 l... |
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 re... | 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(binar... |
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 passe... | 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:
... |
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 mus... | 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:
"""
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)
... |
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: negat... | def decimal_to_binary_iterative(num: int) -> str:
"""
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)
'0b... |
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 in... | # 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 decimal_to_hexadecimal(decimal: float) -> str:
"""
... |
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 ... | import math
# Modified from:
# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js
def decimal_to_octal(num: int) -> str:
"""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))
Tr... |
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_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,
"elect... |
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 | def excel_title_to_column(column_title: str) -> int:
"""
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
... |
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:... | def hex_to_bin(hex_num: str) -> int:
"""
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.
... |
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 t... | hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x'
def hex_to_decimal(hex_string: str) -> int:
"""
Convert a hexadecimal value to its decimal equivalent
#https://www.programiz.com/python-programming/methods/built-in/hex
>>> hex_to_decimal("a")
10
>>> hex_... |
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 1677... | # https://www.geeksforgeeks.org/convert-ip-address-to-integer-and-vice-versa/
def ipv4_to_decimal(ipv4_address: str) -> int:
"""
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 dec... |
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 whi... | 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", # Trailing 's' has been stripped off
"feet": "ft",
"foot": "f... |
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.orgwikiMolarconcen... | def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float:
"""
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
... |
Author: 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' octaltobinaryA... | def octal_to_binary(octal_number: str) -> str:
"""
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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.