Last active
June 7, 2020 11:48
-
-
Save corona10/33043227231f831dead9d0c7ec025d0f to your computer and use it in GitHub Desktop.
json_problem.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def serialize(o): | |
if isinstance(o, int): | |
return str(o) | |
else: | |
return '[' + ','.join(serialize(e) for e in o) + ']' | |
def deserialize(s): | |
idx = 0 | |
def parse_list(s): | |
nonlocal idx | |
ret = [] | |
while idx < len(s): | |
v = s[idx] | |
if v.isnumeric(): | |
num = parse_number(s) | |
ret.append(num) | |
elif v == '[': | |
idx +=1 | |
parsed_list = parse_list(s) | |
ret.append(parsed_list) | |
elif v == ']': | |
idx += 1 | |
return ret | |
else: | |
idx += 1 | |
return ret | |
def parse_number(s): | |
nonlocal idx | |
number = 0 | |
while idx < len(s): | |
v = s[idx] | |
if v.isnumeric(): | |
number *= 10 | |
number += int(v) | |
idx += 1 | |
else: | |
return number | |
return number | |
ret = parse_list(s) | |
return ret[0] | |
def main(): | |
test_cases = [ | |
"345", | |
"[]", | |
"[[[]]]", | |
"[[],[[]]]", | |
"[1,2,3]", | |
"[1,2,[3]]", | |
"[1,[2],3]", | |
"[1,[2,[3,4,[5]]]]", | |
] | |
for t in test_cases: | |
passed = serialize(deserialize(t)) == t | |
print(f"{'PASS' if passed else 'FAIL'}: {t}") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment