Skip to content

Instantly share code, notes, and snippets.

@vrthra
Created April 16, 2022 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrthra/9f8b27d36807d07a9f0f28fd90c89eb0 to your computer and use it in GitHub Desktop.
Save vrthra/9f8b27d36807d07a9f0f28fd90c89eb0 to your computer and use it in GitHub Desktop.
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