Skip to content

Commit 283305b

Browse files
committed
feat(day 12): implement message decoder supporting forward and backward alphabet shifts
1 parent 017a3d4 commit 283305b

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

FreeCodeCamp/CodingQ/en-de.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""
2+
Message Decoder
3+
Given a secret message string, and an integer representing the number of letters that were used to shift the message to encode it, return the decoded string.
4+
5+
A positive number means the message was shifted forward in the alphabet.
6+
A negative number means the message was shifted backward in the alphabet.
7+
Case matters, decoded characters should retain the case of their encoded counterparts.
8+
Non-alphabetical characters should not get decoded.
9+
10+
=========================================================
11+
O/P =============>
12+
13+
decode("Xlmw mw e wigvix qiwweki.", 4) should return "This is a secret message."
14+
decode("Byffi Qilfx!", 20) should return "Hello World!"
15+
16+
"""
17+
18+
def decode_own(message, shift):
19+
final = ''
20+
if shift < 0:
21+
for i in message:
22+
if (i != " " and i.isalpha()):
23+
code = ord(i) + shift
24+
final += chr(code)
25+
else:
26+
final += i
27+
else:
28+
for i in message:
29+
if (i != " " and i.isalpha()):
30+
code = ord(i) - shift
31+
final += chr(code)
32+
else:
33+
final += i
34+
35+
return final
36+
37+
38+
39+
def decode(message, shift):
40+
final = ''
41+
if shift > 0:
42+
43+
for i in message:
44+
if i.isalpha():
45+
base = ord('A') if i.isupper() else ord('a')
46+
code = (ord(i) - base - shift) % 26 + base
47+
final += chr(code)
48+
else:
49+
final += i
50+
else:
51+
for i in message:
52+
if i.isalpha():
53+
base = ord('A') if i.isupper() else ord('a')
54+
code = (ord(i) - base - shift) % 26 + base
55+
final += chr(code)
56+
else:
57+
final += i
58+
return final
59+
60+
def decode2(message, shift):
61+
final = ''
62+
for char in message:
63+
if char.isalpha():
64+
# Determine ASCII base depending on case
65+
base = ord('A') if char.isupper() else ord('a')
66+
# Reverse the shift direction for decoding
67+
decoded_char = chr((ord(char) - base - shift) % 26 + base)
68+
final += decoded_char
69+
else:
70+
# Keep non-alphabet characters as-is
71+
final += char
72+
return final
73+
74+
print(decode("Zqd xnt njzx?", -1))
75+
76+
77+
# print(decode("Xlmw mw e wigvix qiwweki.", 4))

0 commit comments

Comments
 (0)