-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathendecode-protobuf.py
More file actions
executable file
·56 lines (39 loc) · 1.44 KB
/
endecode-protobuf.py
File metadata and controls
executable file
·56 lines (39 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python3
""" endecode-protobuf.py at https://github.com/wilsonmar/python-samples/blob/main/endecode-protobuf.py
STATUS: Kinda working - not putting # between commas in rawlist.
"v003 + Dockstrong :endecode-protobuf.py"
Encodes/decodes a comma-separated list so each word in front of a # prefix has a char count, like Protobuf does for gRPC.
From Neetcode at https://youtube.com/shorts/zwUjHW8Exyc?si=zJqvmNgYht_Oajwq
"This is a common interview question".
Tested on macOS 14.5 (23F79) using Python 3.13.
"""
# NOTE: Python requires self to be explicitly defined as the first parameter in instance methods.
# Use self to clearly distinguish between instance variables and local variables within methods.
def encode(strs: list[str]) -> str:
res = ""
for s in strs:
res += str(len(s)) + "#" + s
return res
def decode(s:str) -> list[str]:
res = []
i = 0
while i < len(s):
j = 1
while s[j] != "#":
j += 1
length = int(s[i:j])
i = j + 1
j = i + length
res.append(s[i:j])
i = j
return res
def main():
rawlist = ["I, love, you"]
# NOTE: Can't separate using # because the string can contain that separation character.
#print(f"*** rawlist={rawlist}")
encoded = encode(rawlist)
print(f"*** enecoded={encoded}")
decoded = decode(encoded)
print(f"*** decoded={decoded}")
if __name__ == "__main__":
main()