Created
April 16, 2022 10:21
-
-
Save vrthra/9f8b27d36807d07a9f0f28fd90c89eb0 to your computer and use it in GitHub Desktop.
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 to_stack(ds): | |
expanded = [] | |
to_expand = [ds] | |
while to_expand: | |
ds, *to_expand = to_expand | |
if type(ds) in {list, set, tuple}: | |
expanded.append(type(ds)) | |
expanded.append(len(ds)) | |
to_expand = list(ds) + to_expand | |
elif type(ds) in {dict}: | |
expanded.append(type(ds)) | |
expanded.append(len(ds)) | |
to_expand = list(ds.items()) + to_expand | |
else: | |
expanded.append(ds) | |
return list(reversed(expanded)) | |
def get_children(result_stk): | |
l = result_stk.pop() | |
return [result_stk.pop() for i in range(l)] | |
def from_stack(stk): | |
i = 0 | |
result_stk = [] | |
while stk: | |
item, *stk = stk | |
if item == list: | |
ds = get_children(result_stk) | |
result_stk.append(ds) | |
elif item == set: | |
ds = get_children(result_stk) | |
result_stk.append(set(ds)) | |
elif item == tuple: | |
ds = get_children(result_stk) | |
result_stk.append(tuple(ds)) | |
elif item == dict: | |
ds = get_children(result_stk) | |
result_stk.append({i[0]:i[1]for i in ds}) | |
else: | |
result_stk.append(item) | |
return result_stk[0] | |
x = [{'a':10, 'b':20, 'c': 30}, ['c', ('d', 'e', 1)]] | |
print(repr(x)) | |
my_stk = to_stack(x) | |
print(repr(my_stk)) | |
my_ds = from_stack(my_stk) | |
print(repr(my_ds)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment