Skip to content

Commit 08452b5

Browse files
committed
added new file
1 parent d62ebf7 commit 08452b5

1 file changed

Lines changed: 86 additions & 0 deletions

File tree

strings/secret_language.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Encoding & Decoding
2+
3+
import random
4+
import string
5+
6+
7+
def random_chars() -> str:
8+
"""
9+
Generate a random string of 3 ASCII letters.
10+
11+
>>> import random
12+
>>> random.seed(42)
13+
>>> random_chars()
14+
'ZoX'
15+
"""
16+
return ''.join(random.choices(string.ascii_letters, k=3))
17+
18+
19+
def random_digits() -> str:
20+
"""
21+
Generate a random string of 3 digits.
22+
23+
>>> import random
24+
>>> random.seed(42)
25+
>>> random_digits()
26+
'638'
27+
"""
28+
return ''.join(random.choices(string.digits, k=3))
29+
30+
31+
def encode(code: str) -> str:
32+
"""
33+
Encode a string by shifting the first character to the end and
34+
wrapping it with random padding of 3 letters and 3 digits on each side.
35+
36+
Reference: https://en.wikipedia.org/wiki/Caesar_cipher
37+
38+
>>> import random
39+
>>> random.seed(42)
40+
>>> encode('hello')
41+
'ZoX638elloh415mJu'
42+
43+
>>> import random
44+
>>> random.seed(42)
45+
>>> encode('hi')
46+
'ZoX638ih415mJu'
47+
"""
48+
if len(code) >= 3:
49+
code = code[1:] + code[0]
50+
code = random_chars() + random_digits() + code + random_digits() + random_chars()
51+
else:
52+
code = code[::-1]
53+
code = random_chars() + random_digits() + code + random_digits() + random_chars()
54+
return code
55+
56+
57+
def decode(code: str) -> str:
58+
"""
59+
Decode an encoded string by stripping the random padding and
60+
reversing the character shift.
61+
62+
>>> import random
63+
>>> random.seed(42)
64+
>>> decode(encode('hello'))
65+
'hello'
66+
67+
>>> import random
68+
>>> random.seed(42)
69+
>>> decode(encode('hi'))
70+
'hi'
71+
"""
72+
code = code[6:-6]
73+
if len(code) >= 3:
74+
code = code[-1] + code[:-1]
75+
else:
76+
code = code[::-1]
77+
return code
78+
79+
80+
if __name__ == "__main__":
81+
code = input("Enter the code: ")
82+
encoded = encode(code)
83+
decoded = decode(encoded)
84+
print(f"Original → {code}")
85+
print(f"Encoded → {encoded}")
86+
print(f"Decoded → {decoded}")v

0 commit comments

Comments
 (0)