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 intersections 0 Return True if this number is power of 2 or False otherwise. ispoweroftwo0 True ispoweroftwo1 True ispoweroftwo2 True ispoweroftwo4 True ispoweroftwo6 False ispoweroftwo8 True ispoweroftwo17 False ispoweroftwo1 Traceback most recent call last: ... ValueError: number must not be negative ispoweroftwo1.2 Traceback most recent call last: ... TypeError: unsupported operand types for : 'float' and 'float' Test all powers of 2 from 0 to 10,000 allispoweroftwoint2 i for i in range10000 True | 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(8)
True
>>> is_power_of_two(17)
False
>>> is_power_of_two(-1)
Traceback (most recent call last):
...
ValueError: number must not be negative
>>> is_power_of_two(1.2)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for &: 'float' and 'float'
# Test all powers of 2 from 0 to 10,000
>>> all(is_power_of_two(int(2 ** i)) for i in range(10000))
True
"""
if number < 0:
raise ValueError("number must not be negative")
return number & (number - 1) == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
|
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 0b10 4 0b100 8 0b1000 16 0b10000 Exit Return the largest power of two less than or equal to a number. largestpowoftwolenum0 0 largestpowoftwolenum1 1 largestpowoftwolenum1 0 largestpowoftwolenum3 2 largestpowoftwolenum15 8 largestpowoftwolenum99 64 largestpowoftwolenum178 128 largestpowoftwolenum999999 524288 largestpowoftwolenum99.9 Traceback most recent call last: ... TypeError: Input value must be a 'int' type | 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_of_two_le_num(15)
8
>>> largest_pow_of_two_le_num(99)
64
>>> largest_pow_of_two_le_num(178)
128
>>> largest_pow_of_two_le_num(999999)
524288
>>> largest_pow_of_two_le_num(99.9)
Traceback (most recent call last):
...
TypeError: Input value must be a 'int' type
"""
if isinstance(number, float):
raise TypeError("Input value must be a 'int' type")
if number <= 0:
return 0
res = 1
while (res << 1) <= number:
res <<= 1
return res
if __name__ == "__main__":
import doctest
doctest.testmod()
|
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, 1 3 findmissingnumber6, 1, 5, 3, 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, 0])
2
>>> find_missing_number([-4, -3, -1, 0])
-2
>>> find_missing_number([-2, 2, 1, 3, 0])
-1
>>> find_missing_number([1, 3, 4, 5, 6])
2
>>> find_missing_number([6, 5, 4, 2, 1])
3
>>> find_missing_number([6, 1, 5, 3, 4])
2
"""
low = min(nums)
high = max(nums)
missing_number = high
for i in range(low, high):
missing_number ^= i ^ nums[i - low]
return missing_number
if __name__ == "__main__":
import doctest
doctest.testmod()
|
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 differentsigns1, 1 False differentsigns1000000000000000000000000000, 1000000000000000000000000000 True differentsigns1000000000000000000000000000, 1000000000000000000000000000 True differentsigns50, 278 False differentsigns0, 2 False differentsigns2, 0 False | 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_signs(-1000000000000000000000000000, 1000000000000000000000000000)
True
>>> different_signs(50, 278)
False
>>> different_signs(0, 2)
False
>>> different_signs(2, 0)
False
"""
return num1 ^ num2 < 0
if __name__ == "__main__":
import doctest
doctest.testmod()
|
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 be a power of 2 and the set bit should be at an odd position. Return True if this number is power of 4 or False otherwise. powerof40 Traceback most recent call last: ... ValueError: number must be positive powerof41 True powerof42 False powerof44 True powerof46 False powerof48 False powerof417 False powerof464 True powerof41 Traceback most recent call last: ... ValueError: number must be positive powerof41.2 Traceback most recent call last: ... TypeError: number must be an integer | 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
>>> power_of_4(6)
False
>>> power_of_4(8)
False
>>> power_of_4(17)
False
>>> power_of_4(64)
True
>>> power_of_4(-1)
Traceback (most recent call last):
...
ValueError: number must be positive
>>> power_of_4(1.2)
Traceback (most recent call last):
...
TypeError: number must be an integer
"""
if not isinstance(number, int):
raise TypeError("number must be an integer")
if number <= 0:
raise ValueError("number must be positive")
if number & (number - 1) == 0:
c = 0
while number:
c += 1
number >>= 1
return c % 2 == 1
else:
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
|
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 conducted on a object of type str Take in an 32 bit integer, reverse its bits, return a string of reverse bits result of a reversebit and operation on the integer provided. reversebit25 '00000000000000000000000000011001' reversebit37 '00000000000000000000000000100101' reversebit21 '00000000000000000000000000010101' reversebit58 '00000000000000000000000000111010' reversebit0 '00000000000000000000000000000000' reversebit256 '00000000000000000000000100000000' reversebit1 Traceback most recent call last: ... ValueError: the value of input must be positive reversebit1.1 Traceback most recent call last: ... TypeError: Input value must be a 'int' type reversebit0 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int' iterator over 1 to 32,since we are dealing with 32 bit integer left shift the bits by unity get the end bit right shift the bits by unity add that bit to our ans | 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'
>>> get_reverse_bit_string("this is not a number")
Traceback (most recent call last):
...
TypeError: operation can not be conducted on a object of type str
"""
if not isinstance(number, int):
msg = (
"operation can not be conducted on a object of type "
f"{type(number).__name__}"
)
raise TypeError(msg)
bit_string = ""
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
return bit_string
def reverse_bit(number: int) -> str:
"""
Take in an 32 bit integer, reverse its bits,
return a string of reverse bits
result of a reverse_bit and operation on the integer provided.
>>> reverse_bit(25)
'00000000000000000000000000011001'
>>> reverse_bit(37)
'00000000000000000000000000100101'
>>> reverse_bit(21)
'00000000000000000000000000010101'
>>> reverse_bit(58)
'00000000000000000000000000111010'
>>> reverse_bit(0)
'00000000000000000000000000000000'
>>> reverse_bit(256)
'00000000000000000000000100000000'
>>> reverse_bit(-1)
Traceback (most recent call last):
...
ValueError: the value of input must be positive
>>> reverse_bit(1.1)
Traceback (most recent call last):
...
TypeError: Input value must be a 'int' type
>>> reverse_bit("0")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if number < 0:
raise ValueError("the value of input must be positive")
elif isinstance(number, float):
raise TypeError("Input value must be a 'int' type")
elif isinstance(number, str):
raise TypeError("'<' not supported between instances of 'str' and 'int'")
result = 0
# iterator over [1 to 32],since we are dealing with 32 bit integer
for _ in range(1, 33):
# left shift the bits by unity
result = result << 1
# get the end bit
end_bit = number % 2
# right shift the bits by unity
number = number >> 1
# add that bit to our ans
result = result | end_bit
return get_reverse_bit_string(result)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
!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: int bool: return number position 1 1 def getbitnumber: int, position: int int: return intnumber 1 position ! 0 if name main: import doctest doctest.testmod | #!/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.
>>> set_bit(0b1101, 1) # 0b1111
15
>>> set_bit(0b0, 5) # 0b100000
32
>>> set_bit(0b1111, 1) # 0b1111
15
"""
return number | (1 << position)
def clear_bit(number: int, position: int) -> int:
"""
Set the bit at position to 0.
Details: perform bitwise and for given number and X.
Where X is a number with all the bits – ones and bit on given
position – zero.
>>> clear_bit(0b10010, 1) # 0b10000
16
>>> clear_bit(0b0, 5) # 0b0
0
"""
return number & ~(1 << position)
def flip_bit(number: int, position: int) -> int:
"""
Flip the bit at position.
Details: perform bitwise xor for given number and X.
Where X is a number with all the bits – zeroes and bit on given
position – one.
>>> flip_bit(0b101, 1) # 0b111
7
>>> flip_bit(0b101, 0) # 0b100
4
"""
return number ^ (1 << position)
def is_bit_set(number: int, position: int) -> bool:
"""
Is the bit at position set?
Details: Shift the bit at position to be the first (smallest) bit.
Then check if the first bit is set by anding the shifted number with 1.
>>> is_bit_set(0b1010, 0)
False
>>> is_bit_set(0b1010, 1)
True
>>> is_bit_set(0b1010, 2)
False
>>> is_bit_set(0b1010, 3)
True
>>> is_bit_set(0b0, 17)
False
"""
return ((number >> position) & 1) == 1
def get_bit(number: int, position: int) -> int:
"""
Get the bit at the given position
Details: perform bitwise and for the given number and X,
Where X is a number with all the bits – zeroes and bit on given position – one.
If the result is not equal to 0, then the bit on the given position is 1, else 0.
>>> get_bit(0b1010, 0)
0
>>> get_bit(0b1010, 1)
1
>>> get_bit(0b1010, 2)
0
>>> get_bit(0b1010, 3)
1
"""
return int((number & (1 << position)) != 0)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
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 | 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 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
even_bits = num & 0xAAAAAAAA
# Get all odd bits - 0x55555555 is a 32-bit number with all odd bits set to 1
odd_bits = num & 0x55555555
# Right shift even bits and left shift odd bits and swap them
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 | 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 (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.
"""
assert (
c % greatest_common_divisor(a, b) == 0
) # greatest_common_divisor(a,b) is in maths directory
(d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below
r = c / d
return (r * x, r * y)
def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None:
"""
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
"""
(x0, y0) = diophantine(a, b, c) # Initial value
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]:
"""
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)
"""
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 | 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.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 | 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 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 | 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]])
"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"
"""
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:
"""
Main function to create and simplify a K-Map.
>>> main()
[0, 1]
[1, 1]
Simplified Expression:
A'B + AB' + AB
"""
kmap = [[0, 1], [1, 1]]
# Manually generate the product of [0, 1] and [0, 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 | 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 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
"""
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 | 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
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 | 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__":
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 ' | 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 == 0)
def truth_table(func: Callable) -> str:
"""
>>> 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 |
"""
def make_table_row(items: list | tuple) -> str:
"""
>>> make_table_row(("One", "Two", "Three"))
'| One | Two | Three |'
"""
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 | 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.geeksforgeeks.orglogicgatesinpython Calculate OR of the input values orgate0, 0 0 orgate0, 1 1 orgate1, 0 1 orgate1, 1 1 | 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
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 | 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)
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]:
"""
>>> check(['0.00.01.5'])
['0.00.01.5']
"""
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]:
"""
>>> decimal_to_binary(3,[1.5])
['0.00.01.5']
"""
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:
"""
>>> is_for_table('__1','011',2)
True
>>> is_for_table('01_','001',1)
False
"""
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]:
"""
>>> selection([[1]],['0.00.01.5'])
['0.00.01.5']
>>> selection([[1]],['0.00.01.5'])
['0.00.01.5']
"""
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]]:
"""
>>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5'])
[[1]]
"""
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 | 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
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 | 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
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 | 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, 0, 0, 0, 0],
]
# Define blinker example
BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
def new_generation(cells: list[list[int]]) -> list[list[int]]:
"""
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]]
"""
next_generation = []
for i in range(len(cells)):
next_generation_row = []
for j in range(len(cells[i])):
# Get the number of live neighbours
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]
# 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.
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]:
"""
Generates a list of images of subsequent Game of Life states.
"""
images = []
for _ in range(frames):
# Create output image
img = Image.new("RGB", (len(cells[0]), len(cells)))
pixels = img.load()
# Save cells to image
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)
# Save image
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, 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 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. | 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]]:
"""
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
"""
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
# finding dead or alive neighbours count.
for i in neighbours:
for status in i:
if status:
alive += 1
else:
dead += 1
# handling duplicate entry for focus pt.
if pt:
alive -= 1
else:
dead -= 1
# running the rules of game here.
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])
# main working structure of this module.
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:
# do nothing.
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 | 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
(1, 1)
"""
def __init__(self, width: int, height: int) -> None:
# Each square is either True or False where True is white and False is black
self.board = [[True] * width for _ in range(height)]
self.ant_position: tuple[int, int] = (width // 2, height // 2)
# Initially pointing left (similar to the wikipedia image)
# (0 = 0° | 1 = 90° | 2 = 180 ° | 3 = 270°)
self.ant_direction: int = 3
def move_ant(self, axes: plt.Axes | None, display: bool, _frame: int) -> None:
"""
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]]
"""
directions = {
0: (-1, 0), # 0°
1: (0, 1), # 90°
2: (1, 0), # 180°
3: (0, -1), # 270°
}
x, y = self.ant_position
# Turn clockwise or anti-clockwise according to colour of square
if self.board[x][y] is True:
# The square is white so turn 90° clockwise
self.ant_direction = (self.ant_direction + 1) % 4
else:
# The square is black so turn 90° anti-clockwise
self.ant_direction = (self.ant_direction - 1) % 4
# Move ant
move_x, move_y = directions[self.ant_direction]
self.ant_position = (x + move_x, y + move_y)
# Flip colour of square
self.board[x][y] = not self.board[x][y]
if display and axes:
# Display the board on the 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:
"""
Displays the board without delay in a matplotlib plot
to visually understand and track the ant.
>>> _ = LangtonsAnt(WIDTH, HEIGHT)
"""
fig, ax = plt.subplots()
# Assign animation to a variable to prevent it from getting garbage collected
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 | 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(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]]
"""
highway = [[-1] * number_of_cells] # Create a highway without any car
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
) # Place the cars
i += (
randint(1, max_speed * 2) if random_frequency else frequency
) # Arbitrary number, may need tuning
return highway
def get_distance(highway_now: list, car_index: int) -> int:
"""
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
"""
distance = 0
cells = highway_now[car_index + 1 :]
for cell in range(len(cells)): # May need a better name for this
if cells[cell] != -1: # If the cell is not empty then
return distance # we have the distance we wanted
distance += 1
# Here if the car is near the end of the highway
return distance + get_distance(highway_now, -1)
def update(highway_now: list, probability: float, max_speed: int) -> list:
"""
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]
"""
number_of_cells = len(highway_now)
# Beforce calculations, the highway is empty
next_highway = [-1] * number_of_cells
for car_index in range(number_of_cells):
if highway_now[car_index] != -1:
# Add 1 to the current speed of the car and cap the speed
next_highway[car_index] = min(highway_now[car_index] + 1, max_speed)
# Number of empty cell before the next car
dn = get_distance(highway_now, car_index) - 1
# We can't have the car causing an accident
next_highway[car_index] = min(next_highway[car_index], dn)
if random() < probability:
# Randomly, a driver will slow down
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:
"""
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]]
"""
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:
# Change the position based on the speed (with % to create the loop)
index = (car_index + speed) % number_of_cells
# Commit the change of position
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 | 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)
[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]
"""
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]) # 31
next_generation = []
for i in range(population):
# Get the neighbors of each cell
# Handle neighbours outside bounds by using 0 as their value
left_neighbor = 0 if i == 0 else cells[time][i - 1]
right_neighbor = 0 if i == population - 1 else cells[time][i + 1]
# Define a new cell and add it to the new generation
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:
"""
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
img = Image.new("RGB", (len(cells[0]), len(cells)))
pixels = img.load()
# Generates image
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)
# Uncomment to save the image
# img.save(f"rule_{rule_num}.png")
img.show()
|
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 result in one of the three possible results. The initial energy value of predator entities The energy value provided when consuming prey The number of entities to delete from the unbalanced side Represents an entity either prey or predator. e EntityTrue, coords0, 0 e.prey True e.coords 0, 0 e.alive True The row, col pos of the entity e EntityTrue, coords0, 0 e.resetreproductiontime e.remainingreproductiontime PREYREPRODUCTIONTIME True e EntityFalse, coords0, 0 e.resetreproductiontime e.remainingreproductiontime PREDATORREPRODUCTIONTIME True EntitypreyTrue, coords1, 1 EntitypreyTrue, coords1, 1, remainingreproductiontime5 EntitypreyFalse, coords2, 1 doctest: NORMALIZEWHITESPACE EntitypreyFalse, coords2, 1, remainingreproductiontime20, energyvalue15 Represents the main WaTor algorithm. :attr timepassed: A function that is called every time time passes a chronon in order to visually display the new WaTor planet. The timepassed function can block using time.sleep to slow the algorithm progression. wt WaTor10, 15 wt.width 10 wt.height 15 lenwt.planet 15 lenwt.planet0 10 lenwt.getentities PREDATORINITIALCOUNT PREYINITIALCOUNT True Populate planet with predators and prey randomly Ease of access for testing wt WaTorWIDTH, HEIGHT planet ... None, None, None, ... None, EntityTrue, coords1, 1, None ... wt.setplanetplanet wt.planet planet True wt.width 3 wt.height 2 Adds an entity, making sure the entity does not override another entity wt WaTorWIDTH, HEIGHT wt.setplanetNone, None, None, None wt.addentityTrue lenwt.getentities 1 wt.addentityFalse lenwt.getentities 2 Returns a list of all the entities within the planet. wt WaTorWIDTH, HEIGHT lenwt.getentities PREDATORINITIALCOUNT PREYINITIALCOUNT True Balances predators and preys so that prey can not dominate the predators, blocking up space for them to reproduce. wt WaTorWIDTH, HEIGHT for i in range2000: ... row, col i HEIGHT, i WIDTH ... wt.planetrowcol EntityTrue, coordsrow, col entities lenwt.getentities wt.balancepredatorsandprey lenwt.getentities entities False Returns all the prey entities around N, S, E, W a predator entity. Subtly different to the trytomovetounoccupied square. wt WaTorWIDTH, HEIGHT wt.setplanet ... None, EntityTrue, 0, 1, None, ... None, EntityFalse, 1, 1, None, ... None, EntityTrue, 2, 1, None wt.getsurroundingprey ... EntityFalse, 1, 1 doctest: NORMALIZEWHITESPACE EntitypreyTrue, coords0, 1, remainingreproductiontime5, EntitypreyTrue, coords2, 1, remainingreproductiontime5 wt.setplanetEntityFalse, 0, 0 wt.getsurroundingpreyEntityFalse, 0, 0 wt.setplanet ... EntityTrue, 0, 0, EntityFalse, 1, 0, EntityFalse, 2, 0, ... None, EntityFalse, 1, 1, EntityTrue, 2, 1, ... None, None, None wt.getsurroundingpreyEntityFalse, 1, 0 EntitypreyTrue, coords0, 0, remainingreproductiontime5 Attempts to move to an unoccupied neighbouring square in either of the four directions North, South, East, West. If the move was successful and the remainingreproduction time is equal to 0, then a new prey or predator can also be created in the previous square. :param directionorders: Ordered list like priority queue depicting order to attempt to move. Removes any systematic approach of checking neighbouring squares. planet ... None, None, None, ... None, EntityTrue, coords1, 1, None, ... None, None, None ... wt WaTorWIDTH, HEIGHT wt.setplanetplanet wt.moveandreproduceEntityTrue, coords1, 1, directionordersN wt.planet doctest: NORMALIZEWHITESPACE None, EntitypreyTrue, coords0, 1, remainingreproductiontime4, None, None, None, None, None, None, None wt.planet00 EntityTrue, coords0, 0 wt.moveandreproduceEntityTrue, coords0, 1, ... directionordersN, W, E, S wt.planet doctest: NORMALIZEWHITESPACE EntitypreyTrue, coords0, 0, remainingreproductiontime5, None, EntitypreyTrue, coords0, 2, remainingreproductiontime4, None, None, None, None, None, None wt.planet01 wt.planet02 wt.planet02 None wt.moveandreproduceEntityTrue, coords0, 1, ... directionordersN, W, S, E wt.planet doctest: NORMALIZEWHITESPACE EntitypreyTrue, coords0, 0, remainingreproductiontime5, None, None, None, EntitypreyTrue, coords1, 1, remainingreproductiontime4, None, None, None, None wt WaTorWIDTH, HEIGHT reproducableentity EntityFalse, coords0, 1 reproducableentity.remainingreproductiontime 0 wt.planet None, reproducableentity wt.moveandreproducereproducableentity, ... directionordersN, W, S, E wt.planet doctest: NORMALIZEWHITESPACE EntitypreyFalse, coords0, 0, remainingreproductiontime20, energyvalue15, EntitypreyFalse, coords0, 1, remainingreproductiontime20, energyvalue15 Weight adjacent locations Move entity to empty adjacent square 2. See if it possible to reproduce in previous square Check if the entities on the planet is less than the max limit Reproduce in previous square Performs the actions for a prey entity For prey the rules are: 1. At each chronon, a prey moves randomly to one of the adjacent unoccupied squares. If there are no free squares, no movement takes place. 2. Once a prey has survived a certain number of chronons it may reproduce. This is done as it moves to a neighbouring square, leaving behind a new prey in its old position. Its reproduction time is also reset to zero. wt WaTorWIDTH, HEIGHT reproducableentity EntityTrue, coords0, 1 reproducableentity.remainingreproductiontime 0 wt.planet None, reproducableentity wt.performpreyactionsreproducableentity, ... directionordersN, W, S, E wt.planet doctest: NORMALIZEWHITESPACE EntitypreyTrue, coords0, 0, remainingreproductiontime5, EntitypreyTrue, coords0, 1, remainingreproductiontime5 Performs the actions for a predator entity :param occupiedbypreycoords: Move to this location if there is prey there For predators the rules are: 1. At each chronon, a predator moves randomly to an adjacent square occupied by a prey. If there is none, the predator moves to a random adjacent unoccupied square. If there are no free squares, no movement takes place. 2. At each chronon, each predator is deprived of a unit of energy. 3. Upon reaching zero energy, a predator dies. 4. If a predator moves to a square occupied by a prey, it eats the prey and earns a certain amount of energy. 5. Once a predator has survived a certain number of chronons it may reproduce in exactly the same way as the prey. wt WaTorWIDTH, HEIGHT wt.setplanetEntityTrue, coords0, 0, EntityFalse, coords0, 1 wt.performpredatoractionsEntityFalse, coords0, 1, 0, 0, wt.planet doctest: NORMALIZEWHITESPACE EntitypreyFalse, coords0, 0, remainingreproductiontime20, energyvalue19, None 3. If the entity has 0 energy, it will die 1. Move to entity if possible Kill the prey Move onto prey 4. Eats the prey and earns energy 5. If it has survived the certain number of chronons it will also reproduce in this function 2. Each chronon, the predator is deprived of a unit of energy Emulate time passing by looping iterationcount times wt WaTorWIDTH, HEIGHT wt.runiterationcountPREDATORINITIALENERGYVALUE 1 lenlistfilterlambda entity: entity.prey is False, ... wt.getentities PREDATORINITIALCOUNT True Generate list of all entities in order to randomly pop an entity at a time to simulate true randomness This removes the systematic approach of iterating through each entity width by height Create list of surrounding prey Again, randomly shuffle directions Balance out the predators and prey Call timepassed function for WaTor planet visualisation in a terminal or a graph. Visually displays the WaTor planet using an ascii code in terminal to clear and reprint the WaTor planet at intervals. Uses ascii colour codes to colourfully display the predators and prey. 0x60f197 Prey 0xfffff Predator x wt WaTor30, 30 wt.setplanet ... EntityTrue, coords0, 0, EntityFalse, coords0, 1, None, ... EntityFalse, coords1, 0, None, EntityFalse, coords1, 2, ... None, EntityTrue, coords2, 1, None ... visualisewt, 0, colourFalse doctest: NORMALIZEWHITESPACE x . x . x . . BLANKLINE Iteration: 0 Prey count: 2 Predator count: 3 Iterate over every entity in the planet Block the thread to be able to visualise seeing the algorithm | 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 before reproducing
PREDATOR_INITIAL_COUNT = 50 # The initial number of predator entities
# The initial energy value of predator entities
PREDATOR_INITIAL_ENERGY_VALUE = 15
# The energy value provided when consuming prey
PREDATOR_FOOD_VALUE = 5
PREDATOR_REPRODUCTION_TIME = 20 # The chronons before reproducing
MAX_ENTITIES = 500 # The max number of organisms on the board
# The number of entities to delete from the unbalanced side
DELETE_UNBALANCED_ENTITIES = 50
class Entity:
"""
Represents an entity (either prey or predator).
>>> e = Entity(True, coords=(0, 0))
>>> e.prey
True
>>> e.coords
(0, 0)
>>> e.alive
True
"""
def __init__(self, prey: bool, coords: tuple[int, int]) -> None:
self.prey = prey
# The (row, col) pos of the entity
self.coords = coords
self.remaining_reproduction_time = (
PREY_REPRODUCTION_TIME if prey else PREDATOR_REPRODUCTION_TIME
)
self.energy_value = None if prey is True else PREDATOR_INITIAL_ENERGY_VALUE
self.alive = True
def reset_reproduction_time(self) -> None:
"""
>>> e = Entity(True, coords=(0, 0))
>>> e.reset_reproduction_time()
>>> e.remaining_reproduction_time == PREY_REPRODUCTION_TIME
True
>>> e = Entity(False, coords=(0, 0))
>>> e.reset_reproduction_time()
>>> e.remaining_reproduction_time == PREDATOR_REPRODUCTION_TIME
True
"""
self.remaining_reproduction_time = (
PREY_REPRODUCTION_TIME if self.prey is True else PREDATOR_REPRODUCTION_TIME
)
def __repr__(self) -> str:
"""
>>> Entity(prey=True, coords=(1, 1))
Entity(prey=True, coords=(1, 1), remaining_reproduction_time=5)
>>> Entity(prey=False, coords=(2, 1)) # doctest: +NORMALIZE_WHITESPACE
Entity(prey=False, coords=(2, 1),
remaining_reproduction_time=20, energy_value=15)
"""
repr_ = (
f"Entity(prey={self.prey}, coords={self.coords}, "
f"remaining_reproduction_time={self.remaining_reproduction_time}"
)
if self.energy_value is not None:
repr_ += f", energy_value={self.energy_value}"
return f"{repr_})"
class WaTor:
"""
Represents the main Wa-Tor algorithm.
:attr time_passed: A function that is called every time
time passes (a chronon) in order to visually display
the new Wa-Tor planet. The time_passed function can block
using time.sleep to slow the algorithm progression.
>>> wt = WaTor(10, 15)
>>> wt.width
10
>>> wt.height
15
>>> len(wt.planet)
15
>>> len(wt.planet[0])
10
>>> len(wt.get_entities()) == PREDATOR_INITIAL_COUNT + PREY_INITIAL_COUNT
True
"""
time_passed: Callable[["WaTor", int], None] | None
def __init__(self, width: int, height: int) -> None:
self.width = width
self.height = height
self.time_passed = None
self.planet: list[list[Entity | None]] = [[None] * width for _ in range(height)]
# Populate planet with predators and prey randomly
for _ in range(PREY_INITIAL_COUNT):
self.add_entity(prey=True)
for _ in range(PREDATOR_INITIAL_COUNT):
self.add_entity(prey=False)
self.set_planet(self.planet)
def set_planet(self, planet: list[list[Entity | None]]) -> None:
"""
Ease of access for testing
>>> wt = WaTor(WIDTH, HEIGHT)
>>> planet = [
... [None, None, None],
... [None, Entity(True, coords=(1, 1)), None]
... ]
>>> wt.set_planet(planet)
>>> wt.planet == planet
True
>>> wt.width
3
>>> wt.height
2
"""
self.planet = planet
self.width = len(planet[0])
self.height = len(planet)
def add_entity(self, prey: bool) -> None:
"""
Adds an entity, making sure the entity does
not override another entity
>>> wt = WaTor(WIDTH, HEIGHT)
>>> wt.set_planet([[None, None], [None, None]])
>>> wt.add_entity(True)
>>> len(wt.get_entities())
1
>>> wt.add_entity(False)
>>> len(wt.get_entities())
2
"""
while True:
row, col = randint(0, self.height - 1), randint(0, self.width - 1)
if self.planet[row][col] is None:
self.planet[row][col] = Entity(prey=prey, coords=(row, col))
return
def get_entities(self) -> list[Entity]:
"""
Returns a list of all the entities within the planet.
>>> wt = WaTor(WIDTH, HEIGHT)
>>> len(wt.get_entities()) == PREDATOR_INITIAL_COUNT + PREY_INITIAL_COUNT
True
"""
return [entity for column in self.planet for entity in column if entity]
def balance_predators_and_prey(self) -> None:
"""
Balances predators and preys so that prey
can not dominate the predators, blocking up
space for them to reproduce.
>>> wt = WaTor(WIDTH, HEIGHT)
>>> for i in range(2000):
... row, col = i // HEIGHT, i % WIDTH
... wt.planet[row][col] = Entity(True, coords=(row, col))
>>> entities = len(wt.get_entities())
>>> wt.balance_predators_and_prey()
>>> len(wt.get_entities()) == entities
False
"""
entities = self.get_entities()
shuffle(entities)
if len(entities) >= MAX_ENTITIES - MAX_ENTITIES / 10:
prey = [entity for entity in entities if entity.prey]
predators = [entity for entity in entities if not entity.prey]
prey_count, predator_count = len(prey), len(predators)
entities_to_purge = (
prey[:DELETE_UNBALANCED_ENTITIES]
if prey_count > predator_count
else predators[:DELETE_UNBALANCED_ENTITIES]
)
for entity in entities_to_purge:
self.planet[entity.coords[0]][entity.coords[1]] = None
def get_surrounding_prey(self, entity: Entity) -> list[Entity]:
"""
Returns all the prey entities around (N, S, E, W) a predator entity.
Subtly different to the try_to_move_to_unoccupied square.
>>> wt = WaTor(WIDTH, HEIGHT)
>>> wt.set_planet([
... [None, Entity(True, (0, 1)), None],
... [None, Entity(False, (1, 1)), None],
... [None, Entity(True, (2, 1)), None]])
>>> wt.get_surrounding_prey(
... Entity(False, (1, 1))) # doctest: +NORMALIZE_WHITESPACE
[Entity(prey=True, coords=(0, 1), remaining_reproduction_time=5),
Entity(prey=True, coords=(2, 1), remaining_reproduction_time=5)]
>>> wt.set_planet([[Entity(False, (0, 0))]])
>>> wt.get_surrounding_prey(Entity(False, (0, 0)))
[]
>>> wt.set_planet([
... [Entity(True, (0, 0)), Entity(False, (1, 0)), Entity(False, (2, 0))],
... [None, Entity(False, (1, 1)), Entity(True, (2, 1))],
... [None, None, None]])
>>> wt.get_surrounding_prey(Entity(False, (1, 0)))
[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5)]
"""
row, col = entity.coords
adjacent: list[tuple[int, int]] = [
(row - 1, col), # North
(row + 1, col), # South
(row, col - 1), # West
(row, col + 1), # East
]
return [
ent
for r, c in adjacent
if 0 <= r < self.height
and 0 <= c < self.width
and (ent := self.planet[r][c]) is not None
and ent.prey
]
def move_and_reproduce(
self, entity: Entity, direction_orders: list[Literal["N", "E", "S", "W"]]
) -> None:
"""
Attempts to move to an unoccupied neighbouring square
in either of the four directions (North, South, East, West).
If the move was successful and the remaining_reproduction time is
equal to 0, then a new prey or predator can also be created
in the previous square.
:param direction_orders: Ordered list (like priority queue) depicting
order to attempt to move. Removes any systematic
approach of checking neighbouring squares.
>>> planet = [
... [None, None, None],
... [None, Entity(True, coords=(1, 1)), None],
... [None, None, None]
... ]
>>> wt = WaTor(WIDTH, HEIGHT)
>>> wt.set_planet(planet)
>>> wt.move_and_reproduce(Entity(True, coords=(1, 1)), direction_orders=["N"])
>>> wt.planet # doctest: +NORMALIZE_WHITESPACE
[[None, Entity(prey=True, coords=(0, 1), remaining_reproduction_time=4), None],
[None, None, None],
[None, None, None]]
>>> wt.planet[0][0] = Entity(True, coords=(0, 0))
>>> wt.move_and_reproduce(Entity(True, coords=(0, 1)),
... direction_orders=["N", "W", "E", "S"])
>>> wt.planet # doctest: +NORMALIZE_WHITESPACE
[[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), None,
Entity(prey=True, coords=(0, 2), remaining_reproduction_time=4)],
[None, None, None],
[None, None, None]]
>>> wt.planet[0][1] = wt.planet[0][2]
>>> wt.planet[0][2] = None
>>> wt.move_and_reproduce(Entity(True, coords=(0, 1)),
... direction_orders=["N", "W", "S", "E"])
>>> wt.planet # doctest: +NORMALIZE_WHITESPACE
[[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), None, None],
[None, Entity(prey=True, coords=(1, 1), remaining_reproduction_time=4), None],
[None, None, None]]
>>> wt = WaTor(WIDTH, HEIGHT)
>>> reproducable_entity = Entity(False, coords=(0, 1))
>>> reproducable_entity.remaining_reproduction_time = 0
>>> wt.planet = [[None, reproducable_entity]]
>>> wt.move_and_reproduce(reproducable_entity,
... direction_orders=["N", "W", "S", "E"])
>>> wt.planet # doctest: +NORMALIZE_WHITESPACE
[[Entity(prey=False, coords=(0, 0),
remaining_reproduction_time=20, energy_value=15),
Entity(prey=False, coords=(0, 1), remaining_reproduction_time=20,
energy_value=15)]]
"""
row, col = coords = entity.coords
adjacent_squares: dict[Literal["N", "E", "S", "W"], tuple[int, int]] = {
"N": (row - 1, col), # North
"S": (row + 1, col), # South
"W": (row, col - 1), # West
"E": (row, col + 1), # East
}
# Weight adjacent locations
adjacent: list[tuple[int, int]] = []
for order in direction_orders:
adjacent.append(adjacent_squares[order])
for r, c in adjacent:
if (
0 <= r < self.height
and 0 <= c < self.width
and self.planet[r][c] is None
):
# Move entity to empty adjacent square
self.planet[r][c] = entity
self.planet[row][col] = None
entity.coords = (r, c)
break
# (2.) See if it possible to reproduce in previous square
if coords != entity.coords and entity.remaining_reproduction_time <= 0:
# Check if the entities on the planet is less than the max limit
if len(self.get_entities()) < MAX_ENTITIES:
# Reproduce in previous square
self.planet[row][col] = Entity(prey=entity.prey, coords=coords)
entity.reset_reproduction_time()
else:
entity.remaining_reproduction_time -= 1
def perform_prey_actions(
self, entity: Entity, direction_orders: list[Literal["N", "E", "S", "W"]]
) -> None:
"""
Performs the actions for a prey entity
For prey the rules are:
1. At each chronon, a prey moves randomly to one of the adjacent unoccupied
squares. If there are no free squares, no movement takes place.
2. Once a prey has survived a certain number of chronons it may reproduce.
This is done as it moves to a neighbouring square,
leaving behind a new prey in its old position.
Its reproduction time is also reset to zero.
>>> wt = WaTor(WIDTH, HEIGHT)
>>> reproducable_entity = Entity(True, coords=(0, 1))
>>> reproducable_entity.remaining_reproduction_time = 0
>>> wt.planet = [[None, reproducable_entity]]
>>> wt.perform_prey_actions(reproducable_entity,
... direction_orders=["N", "W", "S", "E"])
>>> wt.planet # doctest: +NORMALIZE_WHITESPACE
[[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5),
Entity(prey=True, coords=(0, 1), remaining_reproduction_time=5)]]
"""
self.move_and_reproduce(entity, direction_orders)
def perform_predator_actions(
self,
entity: Entity,
occupied_by_prey_coords: tuple[int, int] | None,
direction_orders: list[Literal["N", "E", "S", "W"]],
) -> None:
"""
Performs the actions for a predator entity
:param occupied_by_prey_coords: Move to this location if there is prey there
For predators the rules are:
1. At each chronon, a predator moves randomly to an adjacent square occupied
by a prey. If there is none, the predator moves to a random adjacent
unoccupied square. If there are no free squares, no movement takes place.
2. At each chronon, each predator is deprived of a unit of energy.
3. Upon reaching zero energy, a predator dies.
4. If a predator moves to a square occupied by a prey,
it eats the prey and earns a certain amount of energy.
5. Once a predator has survived a certain number of chronons
it may reproduce in exactly the same way as the prey.
>>> wt = WaTor(WIDTH, HEIGHT)
>>> wt.set_planet([[Entity(True, coords=(0, 0)), Entity(False, coords=(0, 1))]])
>>> wt.perform_predator_actions(Entity(False, coords=(0, 1)), (0, 0), [])
>>> wt.planet # doctest: +NORMALIZE_WHITESPACE
[[Entity(prey=False, coords=(0, 0),
remaining_reproduction_time=20, energy_value=19), None]]
"""
assert entity.energy_value is not None # [type checking]
# (3.) If the entity has 0 energy, it will die
if entity.energy_value == 0:
self.planet[entity.coords[0]][entity.coords[1]] = None
return
# (1.) Move to entity if possible
if occupied_by_prey_coords is not None:
# Kill the prey
prey = self.planet[occupied_by_prey_coords[0]][occupied_by_prey_coords[1]]
assert prey is not None
prey.alive = False
# Move onto prey
self.planet[occupied_by_prey_coords[0]][occupied_by_prey_coords[1]] = entity
self.planet[entity.coords[0]][entity.coords[1]] = None
entity.coords = occupied_by_prey_coords
# (4.) Eats the prey and earns energy
entity.energy_value += PREDATOR_FOOD_VALUE
else:
# (5.) If it has survived the certain number of chronons it will also
# reproduce in this function
self.move_and_reproduce(entity, direction_orders)
# (2.) Each chronon, the predator is deprived of a unit of energy
entity.energy_value -= 1
def run(self, *, iteration_count: int) -> None:
"""
Emulate time passing by looping iteration_count times
>>> wt = WaTor(WIDTH, HEIGHT)
>>> wt.run(iteration_count=PREDATOR_INITIAL_ENERGY_VALUE - 1)
>>> len(list(filter(lambda entity: entity.prey is False,
... wt.get_entities()))) >= PREDATOR_INITIAL_COUNT
True
"""
for iter_num in range(iteration_count):
# Generate list of all entities in order to randomly
# pop an entity at a time to simulate true randomness
# This removes the systematic approach of iterating
# through each entity width by height
all_entities = self.get_entities()
for __ in range(len(all_entities)):
entity = all_entities.pop(randint(0, len(all_entities) - 1))
if entity.alive is False:
continue
directions: list[Literal["N", "E", "S", "W"]] = ["N", "E", "S", "W"]
shuffle(directions) # Randomly shuffle directions
if entity.prey:
self.perform_prey_actions(entity, directions)
else:
# Create list of surrounding prey
surrounding_prey = self.get_surrounding_prey(entity)
surrounding_prey_coords = None
if surrounding_prey:
# Again, randomly shuffle directions
shuffle(surrounding_prey)
surrounding_prey_coords = surrounding_prey[0].coords
self.perform_predator_actions(
entity, surrounding_prey_coords, directions
)
# Balance out the predators and prey
self.balance_predators_and_prey()
if self.time_passed is not None:
# Call time_passed function for Wa-Tor planet
# visualisation in a terminal or a graph.
self.time_passed(self, iter_num)
def visualise(wt: WaTor, iter_number: int, *, colour: bool = True) -> None:
"""
Visually displays the Wa-Tor planet using
an ascii code in terminal to clear and re-print
the Wa-Tor planet at intervals.
Uses ascii colour codes to colourfully display
the predators and prey.
(0x60f197) Prey = #
(0xfffff) Predator = x
>>> wt = WaTor(30, 30)
>>> wt.set_planet([
... [Entity(True, coords=(0, 0)), Entity(False, coords=(0, 1)), None],
... [Entity(False, coords=(1, 0)), None, Entity(False, coords=(1, 2))],
... [None, Entity(True, coords=(2, 1)), None]
... ])
>>> visualise(wt, 0, colour=False) # doctest: +NORMALIZE_WHITESPACE
# x .
x . x
. # .
<BLANKLINE>
Iteration: 0 | Prey count: 2 | Predator count: 3 |
"""
if colour:
__import__("os").system("")
print("\x1b[0;0H\x1b[2J\x1b[?25l")
reprint = "\x1b[0;0H" if colour else ""
ansi_colour_end = "\x1b[0m " if colour else " "
planet = wt.planet
output = ""
# Iterate over every entity in the planet
for row in planet:
for entity in row:
if entity is None:
output += " . "
else:
if colour is True:
output += (
"\x1b[38;2;96;241;151m"
if entity.prey
else "\x1b[38;2;255;255;15m"
)
output += f" {'#' if entity.prey else 'x'}{ansi_colour_end}"
output += "\n"
entities = wt.get_entities()
prey_count = sum(entity.prey for entity in entities)
print(
f"{output}\n Iteration: {iter_number} | Prey count: {prey_count} | "
f"Predator count: {len(entities) - prey_count} | {reprint}"
)
# Block the thread to be able to visualise seeing the algorithm
sleep(0.05)
if __name__ == "__main__":
import doctest
doctest.testmod()
wt = WaTor(WIDTH, HEIGHT)
wt.time_passed = visualise
wt.run(iteration_count=100_000)
|
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(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()
|
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 substitution cipher.' key getrandomkey msg This is a test! decryptmessagekey, encryptmessagekey, msg msg True main | 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) -> None:
if mode == "encrypt":
if key_a == 1:
sys.exit(
"The affine cipher becomes weak when key "
"A is set to 1. Choose different key"
)
if key_b == 0:
sys.exit(
"The affine cipher becomes weak when key "
"B is set to 0. Choose different key"
)
if key_a < 0 or key_b < 0 or key_b > len(SYMBOLS) - 1:
sys.exit(
"Key A must be greater than 0 and key B must "
f"be between 0 and {len(SYMBOLS) - 1}."
)
if gcd_by_iterative(key_a, len(SYMBOLS)) != 1:
sys.exit(
f"Key A {key_a} and the symbol set size {len(SYMBOLS)} "
"are not relatively prime. Choose a different key."
)
def encrypt_message(key: int, message: str) -> str:
"""
>>> encrypt_message(4545, 'The affine cipher is a type of monoalphabetic '
... 'substitution cipher.')
'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi'
"""
key_a, key_b = divmod(key, len(SYMBOLS))
check_keys(key_a, key_b, "encrypt")
cipher_text = ""
for symbol in message:
if symbol in SYMBOLS:
sym_index = SYMBOLS.find(symbol)
cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(SYMBOLS)]
else:
cipher_text += symbol
return cipher_text
def decrypt_message(key: int, message: str) -> str:
"""
>>> decrypt_message(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF'
... '{xIp~{HL}Gi')
'The affine cipher is a type of monoalphabetic substitution cipher.'
"""
key_a, key_b = divmod(key, len(SYMBOLS))
check_keys(key_a, key_b, "decrypt")
plain_text = ""
mod_inverse_of_key_a = cryptomath.find_mod_inverse(key_a, len(SYMBOLS))
for symbol in message:
if symbol in SYMBOLS:
sym_index = SYMBOLS.find(symbol)
plain_text += SYMBOLS[
(sym_index - key_b) * mod_inverse_of_key_a % len(SYMBOLS)
]
else:
plain_text += symbol
return plain_text
def get_random_key() -> int:
while True:
key_b = random.randint(2, len(SYMBOLS))
key_b = random.randint(2, len(SYMBOLS))
if gcd_by_iterative(key_b, len(SYMBOLS)) == 1 and key_b % len(SYMBOLS) != 0:
return key_b * len(SYMBOLS) + key_b
def main() -> None:
"""
>>> key = get_random_key()
>>> msg = "This is a test!"
>>> decrypt_message(key, encrypt_message(key, msg)) == msg
True
"""
message = input("Enter message: ").strip()
key = int(input("Enter key [2000 - 9000]: ").strip())
mode = input("Encrypt/Decrypt [E/D]: ").strip().lower()
if mode.startswith("e"):
mode = "encrypt"
translated = encrypt_message(key, message)
elif mode.startswith("d"):
mode = "decrypt"
translated = decrypt_message(key, message)
print(f"\n{mode.title()}ed text: \n{translated}")
if __name__ == "__main__":
import doctest
doctest.testmod()
# 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: | 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 <= extract <= 122:
output += chr(219 - extract)
else:
output += i
return output
def atbash(sequence: str) -> str:
"""
>>> atbash("ABCDEFG")
'ZYXWVUT'
>>> atbash("aW;;123BX")
'zD;;123YC'
"""
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:
"""Let's benchmark our functions side-by-side..."""
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 | 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("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
"""
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:
"""
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
"""
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 | 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:
"""
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
"""
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:
"""
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
"""
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. | 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 (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.
return "".join([hex(byte)[2:].zfill(2).upper() for byte in list(data)])
def base16_decode(data: str) -> bytes:
"""
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
if (len(data) % 2) != 0:
raise ValueError(
"""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 set(data) <= set("0123456789ABCDEF"):
raise ValueError(
"""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.
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' | 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'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY='
"""
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:
"""
>>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====')
b'Hello World!'
>>> base32_decode(b'GEZDGNBVGY======')
b'123456'
>>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=')
b'some long complex string'
"""
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 | 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 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
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:
# The padding that will be added later
padding = b"=" * ((6 - len(binary_stream) % 6) // 2)
# Append binary_stream with arbitrary binary digits (0's by default) to make its
# length a multiple of 6.
binary_stream += "0" * (6 - len(binary_stream) % 6)
else:
padding = b""
# Encode every 6 binary digits to their corresponding Base64 character
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:
"""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
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)
# In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object
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("=")
# Check if the encoded string contains non base64 characters
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."
# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
if padding:
# Remove padding if there is one
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' | 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''
>>> ascii85_encode(b"12345")
b'0etOA2#'
>>> ascii85_encode(b"base 85")
b'@UX=h+?24'
"""
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:
"""
>>> ascii85_decode(b"")
b''
>>> ascii85_decode(b"0etOA2#")
b'12345'
>>> ascii85_decode(b"@UX=h+?24")
b'base 85'
"""
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()
|
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 PAYUWL JPAIYI' This function decrypts the encrypted text and returns the original text originaltextBDC 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))
# 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:
"""
>>> generate_key("THE GERMAN ATTACK","SECRET")
'SECRETSECRETSECRE'
"""
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
# This function returns the encrypted text
# generated with the help of the key
def cipher_text(message: str, key_new: str) -> str:
"""
>>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE")
'BDC PAYUWL JPAIYI'
"""
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
# This function decrypts the encrypted text
# and returns the original text
def original_text(cipher_text: str, key_new: str) -> str:
"""
>>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE")
'THE GERMAN ATTACK'
"""
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
"""
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:
"""
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
"""
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 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
"""
letter = self.SQUARE[index1 - 1, index2 - 1]
return letter
def encode(self, message: str) -> str:
"""
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
"""
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:
"""
Return the decoded version of message according to the polybius cipher
>>> BifidCipher().decode('qtltbdxrxlk') == 'testmessage'
True
"""
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
|
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 IFWON Decryption using Key 8: LEVWLMP HEVNM Decryption using Key 9: KDUVKLO GDUML Decryption using Key 10: JCTUJKN FCTLK Decryption using Key 11: IBSTIJM EBSKJ Decryption using Key 12: HARSHIL DARJI Decryption using Key 13: GZQRGHK CZQIH Decryption using Key 14: FYPQFGJ BYPHG Decryption using Key 15: EXOPEFI AXOGF Decryption using Key 16: DWNODEH ZWNFE Decryption using Key 17: CVMNCDG YVMED Decryption using Key 18: BULMBCF XULDC Decryption using Key 19: ATKLABE WTKCB Decryption using Key 20: ZSJKZAD VSJBA Decryption using Key 21: YRIJYZC URIAZ Decryption using Key 22: XQHIXYB TQHZY Decryption using Key 23: WPGHWXA SPGYX Decryption using Key 24: VOFGVWZ ROFXW Decryption using Key 25: UNEFUVY QNEWV | 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
Decryption using Key #5: OHYZOPS KHYQP
Decryption using Key #6: NGXYNOR JGXPO
Decryption using Key #7: MFWXMNQ IFWON
Decryption using Key #8: LEVWLMP HEVNM
Decryption using Key #9: KDUVKLO GDUML
Decryption using Key #10: JCTUJKN FCTLK
Decryption using Key #11: IBSTIJM EBSKJ
Decryption using Key #12: HARSHIL DARJI
Decryption using Key #13: GZQRGHK CZQIH
Decryption using Key #14: FYPQFGJ BYPHG
Decryption using Key #15: EXOPEFI AXOGF
Decryption using Key #16: DWNODEH ZWNFE
Decryption using Key #17: CVMNCDG YVMED
Decryption using Key #18: BULMBCF XULDC
Decryption using Key #19: ATKLABE WTKCB
Decryption using Key #20: ZSJKZAD VSJBA
Decryption using Key #21: YRIJYZC URIAZ
Decryption using Key #22: XQHIXYB TQHZY
Decryption using Key #23: WPGHWXA SPGYX
Decryption using Key #24: VOFGVWZ ROFXW
Decryption using Key #25: UNEFUVY QNEWV
"""
for key in range(len(string.ascii_uppercase)):
translated = ""
for symbol in message:
if symbol in string.ascii_uppercase:
num = string.ascii_uppercase.find(symbol)
num = num - key
if num < 0:
num = num + len(string.ascii_uppercase)
translated = translated + string.ascii_uppercase[num]
else:
translated = translated + symbol
print(f"Decryption using Key #{key}: {translated}")
def main() -> None:
message = input("Encrypted message: ")
message = message.upper()
decrypt(message)
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
|
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 | 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: 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
alpha = alphabet or ascii_letters
# The final result string
result = ""
for character in input_string:
if character not in alpha:
# Append without encryption if character is not in the alphabet
result += character
else:
# Get the index of the new key and make sure it isn't too large
new_key = (alpha.index(character) + key) % len(alpha)
# Append the encoded character to the alphabet
result += alpha[new_key]
return result
def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
"""
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
key *= -1
return encrypt(input_string, key, alphabet)
def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]:
"""
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
alpha = alphabet or ascii_letters
# To store data on all the combinations
brute_force_data = {}
# Cycle through each combination
for key in range(1, len(alpha) + 1):
# Decrypt the message and store the result in the data
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")
# get user input
choice = input("\nWhat would you like to do?: ").strip() or "4"
# run functions based on what the user chose
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
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
===========
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'
"""
alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)]
# If the argument is None or the user provided an empty dictionary
if not frequencies_dict:
# Frequencies of letters in the english language (how much they show up)
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:
# Custom frequencies dictionary
frequencies = frequencies_dict
if not case_sensitive:
ciphertext = ciphertext.lower()
# Chi squared statistic values
chi_squared_statistic_values: dict[int, tuple[float, str]] = {}
# cycle through all of the shifts
for shift in range(len(alphabet_letters)):
decrypted_with_shift = ""
# decrypt the message with the shift
for letter in ciphertext:
try:
# Try to index the letter in the alphabet
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:
# Append the character if it isn't in the alphabet
decrypted_with_shift += letter
chi_squared_statistic = 0.0
# Loop through each letter in the decoded message with the shift
for letter in decrypted_with_shift:
if case_sensitive:
letter = letter.lower()
if letter in frequencies:
# Get the amount of times the letter occurs in the message
occurrences = decrypted_with_shift.lower().count(letter)
# Get the excepcted amount of times the letter should appear based
# on letter frequencies
expected = frequencies[letter] * occurrences
# Complete the chi squared statistic formula
chi_letter_value = ((occurrences - expected) ** 2) / expected
# Add the margin of error to the total chi squared statistic
chi_squared_statistic += chi_letter_value
else:
if letter.lower() in frequencies:
# Get the amount of times the letter occurs in the message
occurrences = decrypted_with_shift.count(letter)
# Get the excepcted amount of times the letter should appear based
# on letter frequencies
expected = frequencies[letter] * occurrences
# Complete the chi squared statistic formula
chi_letter_value = ((occurrences - expected) ** 2) / expected
# Add the margin of error to the total chi squared statistic
chi_squared_statistic += chi_letter_value
# Add the data to the chi_squared_statistic_values dictionary
chi_squared_statistic_values[shift] = (
chi_squared_statistic,
decrypted_with_shift,
)
# Get the most likely cipher by finding the cipher with the smallest chi squared
# statistic
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,
)
# Get all the data from the most likely cipher (key, decoded message)
(
most_likely_cipher_chi_squared_value,
decoded_most_likely_cipher,
) = chi_squared_statistic_values[most_likely_cipher]
# Return the data on the most likely shift
return (
most_likely_cipher,
most_likely_cipher_chi_squared_value,
decoded_most_likely_cipher,
)
|
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 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 | 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 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
"""
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): # can quickly check last digit
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."
)
# array bounds provided by analysis
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:
# then we have our last prime to check
plist = primes[:idx]
break
d, s = n - 1, 0
# break up n -1 into a power of 2 (s) and
# remaining odd component
# essentially, solve for d * 2 ** s == n - 1
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)
# see article for analysis explanation for m
if (r == 0 and m == 1) or ((m + 1) % n == 0):
pr = True
# this loop will not determine compositeness
break
if pr:
continue
# if pr is False, then the above loop never evaluated to true,
# and the n MUST be composite
return False
return True
def test_miller_rabin() -> None:
"""Testing a nontrivial (ends in 1, 3, 7, 9) composite
and a prime in each range.
"""
assert not miller_rabin(561)
assert miller_rabin(563)
# 2047
assert not miller_rabin(838_201)
assert miller_rabin(838_207)
# 1_373_653
assert not miller_rabin(17_316_001)
assert miller_rabin(17_316_017)
# 25_326_001
assert not miller_rabin(3_078_386_641)
assert miller_rabin(3_078_386_653)
# 3_215_031_751
assert not miller_rabin(1_713_045_574_801)
assert miller_rabin(1_713_045_574_819)
# 2_152_302_898_747
assert not miller_rabin(2_779_799_728_307)
assert miller_rabin(2_779_799_728_327)
# 3_474_749_660_383
assert not miller_rabin(113_850_023_909_441)
assert miller_rabin(113_850_023_909_527)
# 341_550_071_728_321
assert not miller_rabin(1_275_041_018_848_804_351)
assert miller_rabin(1_275_041_018_848_804_391)
# 3_825_123_056_546_413_051
assert not miller_rabin(79_666_464_458_507_787_791_867)
assert miller_rabin(79_666_464_458_507_787_791_951)
# 318_665_857_834_031_151_167_461
assert not miller_rabin(552_840_677_446_647_897_660_333)
assert miller_rabin(552_840_677_446_647_897_660_359)
# 3_317_044_064_679_887_385_961_981
# upper limit for probabilistic test
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 | 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.
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
"""
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 | 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(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 2048-bit
14: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AACAA68FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 3072-bit
15: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 4096-bit
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,
},
# 6144-bit
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,
},
# 8192-bit
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:
"""
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)
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:
# check if the other public key is valid based on NIST SP800-56
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:
# check if the other public key is valid based on NIST SP800-56
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! | 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 Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996)
# and it seems to run nicely!
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) # select large prime number.
e_1 = primitive_root(p) # one primitive root on modulo p.
d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety.
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 Created by 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'' | 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 --------------------------
rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR"
rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW"
rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC"
# reflector --------------------------
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",
}
# -------------------------- extra rotors --------------------------
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]]:
"""
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
if (unique_rotsel := len(set(rotsel))) < 3:
msg = f"Please use 3 unique rotors (not {unique_rotsel})"
raise Exception(msg)
# Checks if rotor positions are valid
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)
# Validates string and returns dict
pbdict = _plugboard(pb)
return rotpos, rotsel, pbdict
def _plugboard(pbstring: str) -> dict[str, str]:
"""
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)
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(" ", "")
# Checks if all characters are unique
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
# Created the dictionary
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:
"""
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
"""
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 = []
# encryption/decryption process --------------------------
for symbol in text:
if symbol in abc:
# 1st plugboard --------------------------
if symbol in plugboard:
symbol = plugboard[symbol]
# rotor ra --------------------------
index = abc.index(symbol) + rotorpos1
symbol = rotor1[index % len(abc)]
# rotor rb --------------------------
index = abc.index(symbol) + rotorpos2
symbol = rotor2[index % len(abc)]
# rotor rc --------------------------
index = abc.index(symbol) + rotorpos3
symbol = rotor3[index % len(abc)]
# reflector --------------------------
# this is the reason you don't need another machine to decipher
symbol = reflector[symbol]
# 2nd rotors
symbol = abc[rotor3.index(symbol) - rotorpos3]
symbol = abc[rotor2.index(symbol) - rotorpos2]
symbol = abc[rotor1.index(symbol) - rotorpos1]
# 2nd plugboard
if symbol in plugboard:
symbol = plugboard[symbol]
# moves/resets rotor positions
rotorpos1 += 1
if rotorpos1 >= len(abc):
rotorpos1 = 0
rotorpos2 += 1
if rotorpos2 >= len(abc):
rotorpos2 = 0
rotorpos3 += 1
if rotorpos3 >= len(abc):
rotorpos3 = 0
# else:
# pass
# Error could be also raised
# raise ValueError(
# 'Invalid symbol('+repr(symbol)+')')
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. | 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": "--..",
" ": "",
}
# Define possible trigrams of Morse code
MORSE_COMBINATIONS = [
"...",
"..-",
"..x",
".-.",
".--",
".-x",
".x.",
".x-",
".xx",
"-..",
"-.-",
"-.x",
"--.",
"---",
"--x",
"-x.",
"-x-",
"-xx",
"x..",
"x.-",
"x.x",
"x-.",
"x--",
"x-x",
"xx.",
"xx-",
"xxx",
]
# Create a reverse dictionary for Morse code
REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()}
def encode_to_morse(plaintext: str) -> str:
"""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-'
"""
return "x".join([MORSE_CODE_DICT.get(letter.upper(), "") for letter in plaintext])
def encrypt_fractionated_morse(plaintext: str, key: str) -> str:
"""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'
"""
morse_code = encode_to_morse(plaintext)
key = key.upper() + string.ascii_uppercase
key = "".join(sorted(set(key), key=key.find))
# Ensure morse_code length is a multiple of 3
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:
"""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'
"""
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__":
"""
Example usage of Fractionated Morse Cipher.
"""
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' | 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 = numpy.vectorize(lambda x: x % 36)
to_int = numpy.vectorize(round)
def __init__(self, encrypt_key: numpy.ndarray) -> None:
"""
encrypt_key is an NxN numpy array
"""
self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key
self.check_determinant() # validate the determinant of the encryption key
self.break_key = encrypt_key.shape[0]
def replace_letters(self, letter: str) -> int:
"""
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
>>> hill_cipher.replace_letters('T')
19
>>> hill_cipher.replace_letters('0')
26
"""
return self.key_string.index(letter)
def replace_digits(self, num: int) -> str:
"""
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
>>> hill_cipher.replace_digits(19)
'T'
>>> hill_cipher.replace_digits(26)
'0'
"""
return self.key_string[round(num)]
def check_determinant(self) -> None:
"""
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
>>> hill_cipher.check_determinant()
"""
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:
"""
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
>>> hill_cipher.process_text('Testing Hill Cipher')
'TESTINGHILLCIPHERR'
>>> hill_cipher.process_text('hello')
'HELLOO'
"""
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:
"""
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
>>> hill_cipher.encrypt('testing hill cipher')
'WHXYJOLM9C6XT085LL'
>>> hill_cipher.encrypt('hello')
'85FF00'
"""
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:
"""
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
>>> hill_cipher.make_decrypt_key()
array([[ 6, 25],
[ 5, 26]])
"""
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:
"""
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
>>> hill_cipher.decrypt('WHXYJOLM9C6XT085LL')
'TESTINGHILLCIPHERR'
>>> hill_cipher.decrypt('85FF00')
'HELLOO'
"""
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 | 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("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'
"""
keyword = keyword.upper()
plaintext = plaintext.upper()
alphabet_set = set(alphabet)
# create a list of unique characters in the keyword - their order matters
# it determines how we will map plaintext characters to the ciphertext
unique_chars = []
for char in keyword:
if char in alphabet_set and char not in unique_chars:
unique_chars.append(char)
# the number of those unique characters will determine the number of rows
num_unique_chars_in_keyword = len(unique_chars)
# create a shifted version of the alphabet
shifted_alphabet = unique_chars + [
char for char in alphabet if char not in unique_chars
]
# create a modified alphabet by splitting the shifted alphabet into rows
modified_alphabet = [
shifted_alphabet[k : k + num_unique_chars_in_keyword]
for k in range(0, 26, num_unique_chars_in_keyword)
]
# map the alphabet characters to the modified alphabet characters
# going 'vertically' through the modified alphabet - consider columns first
mapping = {}
letter_index = 0
for column in range(num_unique_chars_in_keyword):
for row in modified_alphabet:
# if current row (the last one) is too short, break out of loop
if len(row) <= column:
break
# map current letter to letter in modified alphabet
mapping[alphabet[letter_index]] = row[column]
letter_index += 1
if verbose:
print(mapping)
# create the encrypted text by mapping the plaintext to the modified alphabet
return "".join(mapping[char] if char in mapping else char for char in plaintext)
if __name__ == "__main__":
# example use
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' | 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 == "decrypt" else key
chars_b = key if mode == "decrypt" else LETTERS
translated = ""
# loop through each symbol in the message
for symbol in message:
if symbol.upper() in chars_a:
# encrypt/decrypt the symbol
sym_index = chars_a.find(symbol.upper())
if symbol.isupper():
translated += chars_b[sym_index].upper()
else:
translated += chars_b[sym_index].lower()
else:
# symbol is not in LETTERS, just add it
translated += symbol
return translated
def encrypt_message(key: str, message: str) -> str:
"""
>>> encrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World")
'Pcssi Bidsm'
"""
return translate_message(key, message, "encrypt")
def decrypt_message(key: str, message: str) -> str:
"""
>>> decrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World")
'Itssg Vgksr'
"""
return translate_message(key, message, "decrypt")
def main() -> None:
message = "Hello World"
key = "QWERTYUIOPASDFGHJKLZXCVBNM"
mode = "decrypt" # set to 'encrypt' or '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
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": "-----", "&": ".-...", "@": ".--.-.",
":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", '"': ".-..-.",
"?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-",
"(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/"
} # Exclamation mark is not in ITU-R recommendation
# fmt: on
REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()}
def encrypt(message: str) -> str:
"""
>>> encrypt("Sos!")
'... --- ... -.-.--'
>>> encrypt("SOS!") == encrypt("sos!")
True
"""
return " ".join(MORSE_CODE_DICT[char] for char in message.upper())
def decrypt(message: str) -> str:
"""
>>> decrypt('... --- ... -.-.--')
'SOS!'
"""
return "".join(REVERSE_DICT[char] for char in message.split())
def main() -> None:
"""
>>> s = "".join(MORSE_CODE_DICT)
>>> decrypt(encrypt(s)) == s
True
"""
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' | 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)
>>> 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
"""
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:
"""
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'
"""
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 | 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)
>>> generate_valid_block_size(12)
3
"""
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]:
"""
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]
"""
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]]:
"""
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'
"""
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:
"""
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'
"""
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:
"""
Driver function to pass message to get encrypted, then decrypted.
Example:
>>> main()
Decrypted message: HELLO WORLD
"""
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' | 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:
"""
Prepare the plaintext by up-casing it
and separating repeated letters with X's
"""
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]:
# I and J are used interchangeably to allow
# us to use a 5x5 table (25 letters)
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
# 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
table = []
# copy key chars into the table if they are in `alphabet` ignoring duplicates
for char in key.upper():
if char not in table and char in alphabet:
table.append(char)
# fill the rest of the table in with the remaining alphabet chars
for char in alphabet:
if char not in table:
table.append(char)
return table
def encode(plaintext: str, key: str) -> str:
"""
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'
"""
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: # rectangle
ciphertext += table[row1 * 5 + col2]
ciphertext += table[row2 * 5 + col1]
return ciphertext
def decode(ciphertext: str, key: str) -> str:
"""
Decode the input string using the provided key.
>>> decode("BMZFAZRZDH", "HAZARD")
'FIREHAZARD'
>>> decode("HNBWBPQT", "AUTOMOBILE")
'DRIVINGX'
>>> decode("SLYSSAQS", "CASTLE")
'ATXTACKX'
"""
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: # rectangle
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
"""
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:
"""
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
"""
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 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 self.SQUARE[index1 - 1, index2 - 1]
def encode(self, message: str) -> str:
"""
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
"""
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:
"""
Return the decoded version of message according to the polybius cipher
>>> PolybiusCipher().decode("44154344 32154343112215") == "test message"
True
>>> PolybiusCipher().decode("4415434432154343112215") == "testmessage"
True
"""
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 | 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]]:
"""
>>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE
[('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
('ABCDEFGHIJKLM', 'STUVWXYZNOPQR'), ('ABCDEFGHIJKLM', 'QRSTUVWXYZNOP'),
('ABCDEFGHIJKLM', 'WXYZNOPQRSTUV'), ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST')]
"""
return [alphabet[char] for char in key.upper()]
def encrypt(key: str, words: str) -> str:
"""
>>> encrypt('marvin', 'jessica')
'QRACRWU'
"""
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:
"""
>>> decrypt('marvin', 'QRACRWU')
'JESSICA'
"""
return encrypt(key, words)
def get_position(table: tuple[str, str], char: str) -> tuple[int, int]:
"""
>>> get_position(generate_table('marvin')[0], 'M')
(0, 12)
"""
# `char` is either in the 0th row or the 1st row
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:
"""
>>> get_opponent(generate_table('marvin')[0], 'M')
'T'
"""
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() # Fist ensure that all our tests are passing...
"""
Demo:
Enter key: marvin
Enter text to encrypt: jessica
Encrypted: QRACRWU
Decrypted with key: JESSICA
"""
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 | 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)
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
"""
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) # puts it in bounds
num = min(num, lowest * 2 - num) # creates zigzag pattern
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:
"""
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'
"""
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)] # generates template
for position in range(len(input_string)):
num = position % (lowest * 2) # puts it in bounds
num = min(num, lowest * 2 - num) # creates zigzag pattern
temp_grid[num].append("*")
counter = 0
for row in temp_grid: # fills in the characters
splice = input_string[counter : counter + len(row)]
grid.append(list(splice))
counter += len(row)
output_string = "" # reads as zigzag
for position in range(len(input_string)):
num = position % (lowest * 2) # puts it in bounds
num = min(num, lowest * 2 - num) # creates zigzag pattern
output_string += grid[num][0]
grid[num].pop(0)
return output_string
def bruteforce(input_string: str) -> dict[int, str]:
"""Uses decrypt function by guessing every key
>>> bruteforce("HWe olordll")[4]
'Hello World'
"""
results = {}
for key_guess in range(1, len(input_string)): # tries every key
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 | 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
"""
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 | 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 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]
"""
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 # find the correct factors
else:
break # t is not divisible by 2, break and choose another g
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 | 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]]:
"""
>>> random.seed(0) # for repeatability
>>> public_key, private_key = generate_key(8)
>>> public_key
(26569, 239)
>>> private_key
(26569, 2855)
"""
p = rabin_miller.generate_large_prime(key_size)
q = rabin_miller.generate_large_prime(key_size)
n = p * q
# Generate e that is relatively prime to (p - 1) * (q - 1)
while True:
e = random.randrange(2 ** (key_size - 1), 2 ** (key_size))
if gcd_by_iterative(e, (p - 1) * (q - 1)) == 1:
break
# Calculate d that is mod inverse of e
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()
|
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. :param ciphertext: The ciphertext to be decrypted. :return: The plaintext. key How does the duck know that? said Victor ciphertext runningkeyencryptkey, DEFEND THIS runningkeydecryptkey, ciphertext DEFENDTHIS True | 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()
key = key.replace(" ", "").upper()
key_length = len(key)
ciphertext = []
ord_a = ord("A")
for i, char in enumerate(plaintext):
p = ord(char) - ord_a
k = ord(key[i % key_length]) - ord_a
c = (p + k) % 26
ciphertext.append(chr(c + ord_a))
return "".join(ciphertext)
def running_key_decrypt(key: str, ciphertext: str) -> str:
"""
Decrypts the ciphertext using the Running Key Cipher.
:param key: The running key (long piece of text).
:param ciphertext: The ciphertext to be decrypted.
:return: The plaintext.
"""
ciphertext = ciphertext.replace(" ", "").upper()
key = key.replace(" ", "").upper()
key_length = len(key)
plaintext = []
ord_a = ord("A")
for i, char in enumerate(ciphertext):
c = ord(char) - ord_a
k = ord(key[i % key_length]) - ord_a
p = (c - k) % 26
plaintext.append(chr(p + ord_a))
return "".join(plaintext)
def test_running_key_encrypt() -> None:
"""
>>> key = "How does the duck know that? said Victor"
>>> ciphertext = running_key_encrypt(key, "DEFEND THIS")
>>> running_key_decrypt(key, ciphertext) == "DEFENDTHIS"
True
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
test_running_key_encrypt()
plaintext = input("Enter the plaintext: ").upper()
print(f"\n{plaintext = }")
key = "How does the duck know that? said Victor"
encrypted_text = running_key_encrypt(key, plaintext)
print(f"{encrypted_text = }")
decrypted_text = running_key_decrypt(key, encrypted_text)
print(f"{decrypted_text = }")
|
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' | 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 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()
"""
def __init__(self, passcode: str | None = None) -> None:
"""
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
"""
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: passcode of the cipher object
"""
return "".join(self.__passcode)
def __neg_pos(self, iterlist: list[int]) -> list[int]:
"""
Mutates the list by changing the sign of each alternate element
:param iterlist: takes a list iterable
:return: the mutated list
"""
for i in range(1, len(iterlist), 2):
iterlist[i] *= -1
return iterlist
def __passcode_creator(self) -> list[str]:
"""
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
"""
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]:
"""
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
key_list_options = (
string.ascii_letters + string.digits + string.punctuation + " \t\n"
)
keys_l = []
# creates points known as breakpoints to break the key_list_options at those
# points and pivot each substring
breakpoints = sorted(set(self.__passcode))
temp_list: list[str] = []
# algorithm for creating a new shuffled list, keys_l, out of key_list_options
for i in key_list_options:
temp_list.extend(i)
# checking breakpoints at which to pivot temporary sublist and add it into
# keys_l
if i in breakpoints or i == key_list_options[-1]:
keys_l.extend(temp_list[::-1])
temp_list.clear()
# returning a shuffled keys_l to prevent brute force guessing of shift key
return keys_l
def __make_shift_key(self) -> int:
"""
sum() of the mutated list of ascii values of all characters where the
mutated list is the one returned by __neg_pos()
"""
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:
"""
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'
"""
decoded_message = ""
# decoding shift like Caesar cipher algorithm implementing negative shift or
# reverse shift or left shift
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:
"""
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<'.&>#"
"""
encoded_message = ""
# encoding shift like Caesar cipher algorithm implementing positive shift or
# forward shift or right shift
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:
"""
>>> test_end_to_end()
'Hello, this is a modified Caesar cipher'
"""
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 | 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 = ""
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]:
"""
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
alphabet = [chr(i + 65) for i in range(26)]
# Remove duplicate characters from key
key = remove_duplicates(key.upper())
offset = len(key)
# First fill cipher with key characters
cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)}
# Then map remaining characters in alphabet to
# the alphabet from the beginning
for i in range(len(cipher_alphabet), 26):
char = alphabet[i - offset]
# Ensure we are not mapping letters to letters previously mapped
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:
"""
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!!'
"""
return "".join(cipher_map.get(ch, ch) for ch in message.upper())
def decipher(message: str, cipher_map: dict[str, str]) -> str:
"""
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
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:
"""
Handles I/O
:return: void
"""
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' | 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:
"""
>>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
return translate_message(key, message, "encrypt")
def decrypt_message(key: str, message: str) -> str:
"""
>>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
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' | 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 the ROUTE cipher.
"""
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)
# Append pipe symbol (vertical bar) to identify spaces at the end.
print(f"Output:\n{text + '|'}")
def encrypt_message(key: int, message: str) -> str:
"""
>>> encrypt_message(6, 'Harshil Darji')
'Hlia rDsahrij'
"""
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:
"""
>>> decrypt_message(6, 'Hlia rDsahrij')
'Harshil Darji'
"""
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' | 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": "312", "U": "313",
"V": "321", "W": "322", "X": "323", "Y": "331", "Z": "332", "+": "333",
}
# fmt: off
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:
"""
Arrange the triagram value of each letter of 'message_part' vertically and join
them horizontally.
>>> __encrypt_part('ASK', TEST_CHARACTER_TO_NUMBER)
'132111112'
"""
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]:
"""
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')
"""
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]]:
"""
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
alphabet = alphabet.replace(" ", "").upper()
message = message.replace(" ", "").upper()
# Check length and characters
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!")
# Generate dictionares
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:
"""
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'
"""
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:
"""
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'
"""
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 | 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 + ct)
return ciphertext
def vernam_decrypt(ciphertext: str, key: str) -> str:
"""
>>> vernam_decrypt("RIJVS","KEY")
'HELLO'
"""
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()
# Example usage
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.' | 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:
"""
>>> encrypt_message('HDarji', 'This is Harshil Darji from Dharmaj.')
'Akij ra Odrjqqs Gaisq muod Mphumrs.'
"""
return translate_message(key, message, "encrypt")
def decrypt_message(key: str, message: str) -> str:
"""
>>> decrypt_message('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')
'This is Harshil Darji from Dharmaj.'
"""
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()
|
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 : 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 | 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]:
"""
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
assert isinstance(key, int)
assert isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 256
return [chr(ord(ch) ^ key) for ch in content]
def decrypt(self, content: str, key: int) -> list[str]:
"""
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
assert isinstance(key, int)
assert isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 256
return [chr(ord(ch) ^ key) for ch in content]
def encrypt_string(self, content: str, key: int = 0) -> str:
"""
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
assert isinstance(key, int)
assert isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 256
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def decrypt_string(self, content: str, key: int = 0) -> str:
"""
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
assert isinstance(key, int)
assert isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 256
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def encrypt_file(self, file: str, key: int = 0) -> bool:
"""
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
assert isinstance(file, str)
assert isinstance(key, int)
# make sure key is an appropriate size
key %= 256
try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
# actual encrypt-process
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:
"""
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
assert isinstance(file, str)
assert isinstance(key, int)
# make sure key is an appropriate size
key %= 256
try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
# actual encrypt-process
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()
# 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")
|
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' | 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 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.
"""
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:
"""
: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.
"""
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() # sort the list of rotations in alphabetically order
# make a string composed of the last char of each rotation
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:
"""
: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'
"""
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 | 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]:
"""
Read the file and build a dict of all letters and their
frequencies, then convert the dict into a list of Letters.
"""
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:
"""
Run through the list of Letters and build the min heap
for the Huffman Tree.
"""
response: list[Letter | TreeNode] = letters # type: ignore
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]:
"""
Recursively traverse the Huffman Tree to set each
Letter's bitstring dictionary, and return the list of Letters
"""
if isinstance(root, Letter):
root.bitstring[root.letter] = bitstring
return [root]
treenode: TreeNode = root # type: ignore
letters = []
letters += traverse_tree(treenode.left, bitstring + "0")
letters += traverse_tree(treenode.right, bitstring + "1")
return letters
def huffman(file_path: str) -> None:
"""
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.
"""
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__":
# pass the file path to the huffman function
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 | 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 = 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:
"""
Adds new strings (curr_string + "0", curr_string + "1") to the lexicon
"""
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:
"""
Compresses given data_bits using Lempel–Ziv–Welch compression algorithm
and returns the result as a string
"""
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:
"""
Adds given file's length in front (using Elias gamma coding) of the compressed
string
"""
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:
"""
Writes given to_write string (should only consist of 0's and 1's) as bytes in the
file
"""
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:
"""
Reads source file, compresses it and writes the compressed result in destination
file
"""
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 | 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:08b}"
result += curr_byte
return result
except OSError:
print("File not accessible")
sys.exit()
def decompress_data(data_bits: str) -> str:
"""
Decompresses given data_bits using Lempel–Ziv–Welch compression algorithm
and returns the result as a string
"""
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:
"""
Writes given to_write string (should only consist of 0's and 1's) as bytes in the
file
"""
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:
"""
Removes size prefix, that compressed file should have
Returns the result
"""
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:
"""
Reads source file, decompresses it and writes the result in destination file
"""
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 | 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: str
def __repr__(self) -> str:
"""
>>> token = Token(1, 2, "c")
>>> repr(token)
'(1, 2, c)'
>>> str(token)
'(1, 2, c)'
"""
return f"({self.offset}, {self.length}, {self.indicator})"
class LZ77Compressor:
"""
Class containing compress and decompress methods using LZ77 compression algorithm.
"""
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]:
"""
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)]'
"""
output = []
search_buffer = ""
# while there are still characters in text to compress
while text:
# find the next encoding phrase
# - triplet with offset, length, indicator (the next encoding character)
token = self._find_encoding_token(text, search_buffer)
# 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
search_buffer += text[: token.length + 1]
if len(search_buffer) > self.search_buffer_size:
search_buffer = search_buffer[-self.search_buffer_size :]
# update the text
text = text[token.length + 1 :]
# append the token to output
output.append(token)
return output
def decompress(self, tokens: list[Token]) -> str:
"""
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'
"""
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:
"""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
"""
if not text:
raise ValueError("We need some text to work with.")
# Initialise result parameters to default values
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 the found length is bigger than the current or if it's equal,
# which means it's offset is smaller: update offset and length
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:
"""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
"""
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()
# Initialize compressor class
lz77_compressor = LZ77Compressor(window_size=13, lookahead_buffer_size=6)
# Example
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 | 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__))
# Loading images (original image and compressed image)
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
)
# Value expected: 29.73dB
print("-- First Test --")
print(f"PSNR value is {peak_signal_to_noise_ratio(original, contrast)} dB")
# # Value expected: 31.53dB (Wikipedia Example)
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
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', 2)]
>>> run_length_encode("AAADDDDDDFFFCCCAAVVVV")
[('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)]
"""
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:
"""
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'
"""
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 | 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 main() -> None:
"""
Get images list and annotations list from input dir.
Update new images and annotations.
Save images and annotations in output dir.
"""
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):
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
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]:
"""
- 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_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]:
"""
- 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
"""
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:
"""
Automatic generate random 32 characters.
Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
>>> len(random_chars(32))
32
"""
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. | 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]))
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
"""
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:
"""
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)
"""
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:
"""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. ]])
"""
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:
"""
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)
"""
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:
"""
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]])
"""
return np.where(image > threshold, 1, 0)
def transform(
image: np.ndarray, kind: str, kernel: np.ndarray | None = None
) -> np.ndarray:
"""
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)
"""
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)
# Use padded image when applying convolotion
# to not go out of bounds of the original the image
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
]
# Apply transformation method to the centered section of the image
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:
"""
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)
"""
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:
"""
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)
"""
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]:
"""
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))
"""
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:
"""
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.]])
"""
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]:
"""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
i, j = np.ogrid[0 : matrix.shape[0], 0 : matrix.shape[1]] # np.indices()
# Pre-calculate frequent multiplication and subtraction
prod = np.multiply(i, j)
sub = np.subtract(i, j)
# Calculate numerical value of Maximum Probability
maximum_prob = np.max(matrix)
# Using the definition for each descriptor individually to calculate its 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]))
# 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.
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:
"""
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.])
"""
descriptors = np.array(
[haralick_descriptors(matrix_concurrency(mask, coordinate)) for mask in masks]
)
# Concatenate each individual descriptor into
# one single list containing sequence of descriptors
return np.concatenate(descriptors, axis=None)
def euclidean(point_1: np.ndarray, point_2: np.ndarray) -> np.float32:
"""
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
"""
return np.sqrt(np.sum(np.square(point_1 - point_2)))
def get_distances(descriptors: np.ndarray, base: int) -> list[tuple[int, float]]:
"""
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)]
"""
distances = np.array(
[euclidean(descriptor, descriptors[base]) for descriptor in descriptors]
)
# Normalize distances between range [0, 1]
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 to compare haralick descriptors to
index = int(input())
q_value_list = [int(value) for value in input().split()]
q_value = (q_value_list[0], q_value_list[1])
# Format is the respective filter to apply,
# can be either 1 for the opening filter or else for the closing
parameters = {"format": int(input()), "threshold": int(input())}
# Number of images to perform methods on
b_number = int(input())
files, descriptors = [], []
for _ in range(b_number):
file = input().rstrip()
files.append(file)
# Open given image and calculate morphological filter,
# respective masks and correspondent Harralick Descriptors.
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))
# Transform ordered distances array into a sequence of indexes
# corresponding to original file position
distances = get_distances(np.array(descriptors), index)
indexed_distances = np.array(distances).astype(np.uint8)[:, 0]
# Finally, print distances considering the Haralick descriptions from the base
# file to all other images using the morphology method of choice.
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 | 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
"""
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]]]:
"""
Returns the image with corners identified
img_path : path of the image
output : list of the corner positions, image
"""
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)
# Can change the value
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 | 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 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]])
"""
flow = np.stack((horizontal_flow, vertical_flow), 2)
# Create a grid of all pixel coordinates and subtract the flow to get the
# target pixels coordinates
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)
# Find the locations outside of the original image
invalid = (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]]))
grid[invalid] = 0
warped = image[grid[:, :, 1], grid[:, :, 0]]
# Set pixels at invalid locations to 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]:
"""
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)
"""
if alpha is None:
alpha = 0.1
# Initialize flow
horizontal_flow = np.zeros_like(image0)
vertical_flow = np.zeros_like(image0)
# Prepare kernels for the calculation of the derivatives and the average velocity
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]]
)
# Iteratively refine the flow
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)
# This updates the flow as proposed in the paper (Step 12)
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 | 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()
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 | 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 = ""
NUMBER_IMAGES = 250
def main() -> None:
"""
Get images list and annotations list from input dir.
Update new images and annotations.
Save images and annotations in output dir.
"""
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,
)
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
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]:
"""
- 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_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]:
"""
- 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
"""
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: # top-left
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: # top-right
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: # bottom-left
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: # bottom-right
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])
# Remove bounding box small than scale of filter
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:
"""
Automatic generate random 32 characters.
Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
>>> len(random_chars(32))
32
"""
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
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 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.]])
"""
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
# compute the shape of the output matrix
maxpool_shape = (arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape maxpool_shape
updated_arr = np.zeros((maxpool_shape, maxpool_shape))
while i < arr.shape[0]:
if i + size > arr.shape[0]:
# if the end of the matrix is reached, break
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the maximum of the pooling matrix
updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size])
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
j = 0
mat_j = 0
return updated_arr
# Averagepooling Function
def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray:
"""
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.]])
"""
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
# compute the shape of the output matrix
avgpool_shape = (arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape avgpool_shape
updated_arr = np.zeros((avgpool_shape, avgpool_shape))
while i < arr.shape[0]:
# if the end of the matrix is reached, break
if i + size > arr.shape[0]:
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the average of the pooling matrix
updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size]))
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
j = 0
mat_j = 0
return updated_arr
# Main Function
if __name__ == "__main__":
from doctest import testmod
testmod(name="avgpooling", verbose=True)
# Loading the image
image = Image.open("path_to_image")
# Converting the image to numpy array and maxpooling, displaying the result
# Ensure that the image is a square matrix
Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()
# Converting the image to numpy array and averagepooling, displaying the result
# Ensure that the image is a square matrix
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 | 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": 9,
"Tm": 12,
"Pm": 15,
"Em": 18,
"Zm": 21,
"Ym": 24,
}
def length_conversion(value: float, from_type: str, to_type: str) -> float:
"""
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
"""
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 | 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 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
"""
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 | 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:
"""
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
binary_str = str(binary_str).strip()
# Exceptions
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, | 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)
'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
"""
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: | 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)
'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
"""
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:
"""
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'
"""
decimal = int(decimal)
if decimal in (0, 1): # Exit cases for the recursion
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:
"""
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
"""
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
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:
"""
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
"""
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: | 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))
True
"""
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) # basically /= 8 without remainder if any
# This formatting removes trailing '.0' from `octal`.
return f"0o{int(octal)}"
def main() -> None:
"""Print octal equivalents of decimal numbers."""
print("\n2 in octal is:")
print(decimal_to_octal(2)) # = 2
print("\n8 in octal is:")
print(decimal_to_octal(8)) # = 10
print("\n65 in octal is:")
print(decimal_to_octal(65)) # = 101
print("\n216 in octal is:")
print(decimal_to_octal(216)) # = 330
print("\n512 in octal is:")
print(decimal_to_octal(512)) # = 1000
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 | 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:
"""
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
"""
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 | 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
>>> excel_title_to_column("Z")
26
"""
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 | 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.
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
"""
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 | 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_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_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/
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 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
"""
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}") # noqa: EM102
decimal_ipv4 = (decimal_ipv4 << 8) + int(octet)
return decimal_ipv4
def alt_ipv4_to_decimal(ipv4_address: str) -> int:
"""
>>> alt_ipv4_to_decimal("192.168.0.1")
3232235521
>>> alt_ipv4_to_decimal("10.0.0.255")
167772415
"""
return int("0x" + "".join(f"{int(i):02x}" for i in ipv4_address.split(".")), 16)
def decimal_to_ipv4(decimal_ipv4: int) -> str:
"""
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
"""
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 | 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": "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:
"""
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
"""
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 | 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
>>> molarity_to_normality(2, 3.1, 0.31)
20
>>> molarity_to_normality(4, 11.4, 5.7)
8
"""
return round(float(moles / volume) * nfactor)
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float:
"""
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
"""
return round(float((moles * 0.0821 * temperature) / (volume)))
def moles_to_volume(pressure: float, moles: float, temperature: float) -> float:
"""
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
"""
return round(float((moles * 0.0821 * temperature) / (pressure)))
def pressure_and_volume_to_temperature(
pressure: float, moles: float, volume: float
) -> float:
"""
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
"""
return round(float((pressure * volume) / (0.0821 * moles)))
if __name__ == "__main__":
import doctest
doctest.testmod()
|
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' 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 | 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
>>> 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
"""
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()
|