Skip to content

Commit 4c0c4c1

Browse files
Development (#16)
* caesar cipher * binary to decimal
1 parent b82d43a commit 4c0c4c1

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

ciphers/caesar.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
https://en.wikipedia.org/wiki/Caesar_cipher
3+
"""
4+
5+
6+
def encrypt(original: str, steps: int = 3) -> str:
7+
"""
8+
>>> encrypt("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
9+
'DEFGHIJKLMNOPQRSTUVWXYZABC'
10+
>>> encrypt("abcdefghijklmnopqrstuvwxyz")
11+
'defghijklmnopqrstuvwxyzabc'
12+
"""
13+
original = list(original)
14+
for i in range(0, len(original)):
15+
if original[i].isupper():
16+
original[i] = chr(65 + (ord(original[i]) - 65 + steps) % 26)
17+
elif original[i].islower():
18+
original[i] = chr(97 + (ord(original[i]) - 97 + steps) % 26)
19+
return "".join(original)
20+
21+
22+
def decrypt(password: str, steps: int = 3) -> str:
23+
"""
24+
>>> decrypt("DEFGHIJKLMNOPQRSTUVWXYZABC")
25+
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
26+
>>> decrypt(("defghijklmnopqrstuvwxyzabc"))
27+
'abcdefghijklmnopqrstuvwxyz'
28+
"""
29+
password = list(password)
30+
for i in range(0, len(password)):
31+
if password[i].isupper():
32+
password[i] = chr(65 + (ord(password[i]) - 65 - steps + 26) % 26)
33+
elif password[i].islower():
34+
password[i] = chr(97 + (ord(password[i]) - 97 - steps + 26) % 26)
35+
return "".join(password)
36+
37+
38+
if __name__ == "__main__":
39+
from doctest import testmod
40+
41+
testmod()

conversions/binary_to_decimal.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
https://en.wikipedia.org/wiki/Binary_number
3+
https://en.wikipedia.org/wiki/Decimal
4+
"""
5+
6+
7+
def binary_to_decimal(binary: str) -> int:
8+
"""
9+
>>> binary_to_decimal("0")
10+
0
11+
>>> binary_to_decimal("1")
12+
1
13+
>>> binary_to_decimal("1010")
14+
10
15+
>>> binary_to_decimal("-11101")
16+
-29
17+
"""
18+
is_negative = binary[0] == "-"
19+
binary = binary[1:] if is_negative else binary
20+
decimal = 0
21+
for i in range(0, len(binary)):
22+
decimal += int(binary[i]) * (2 ** (len(binary) - i - 1))
23+
return -decimal if is_negative else decimal
24+
25+
26+
if __name__ == "__main__":
27+
from doctest import testmod
28+
29+
testmod()

0 commit comments

Comments
 (0)