Skip to content

Commit 7fde9ff

Browse files
committed
added new file secret_language
1 parent d62ebf7 commit 7fde9ff

1 file changed

Lines changed: 92 additions & 0 deletions

File tree

strings/Secret_language.py

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

0 commit comments

Comments
 (0)