A recursive list is represented by a chain of pairs. The first element of each pair is the element in the list, and the second is the pair that represents the rest of the list. The second element of the last pair is None, which indicates that the list has ended. We can build this structure using a nested tuple. Example:
(1, (2, (3, (4, None))))
So far I have created a method that converts a tuple of values or a None value to the corresponding rlist. The method is called to_rlist (items). Example:
>>> to_rlist((1, (0, 2), (), 3))
(1, ((0, (2, None)), (None, (3, None))))
How to write an inversion of to_rlist, a function that takes rlist as input and returns the corresponding tuple? The method must be called to_tuple (parameter). An example of what should happen:
>>> x = to_rlist((1, (0, 2), (), 3))
>>> to_tuple(x)
(1, (0, 2), (), 3)
Note. The to_rlist method works as intended.
, :
def to_tuple(L):
if not could_be_rlist(L):
return (L,)
x, y = L
if not x is None and not type(x) is tuple and y is None:
return (x,)
elif x is None and not y is None:
return ((),) + to_tuple(y)
elif not x is None and not y is None:
return to_tuple(x) + to_tuple(y)
( ):
>>> x = to_rlist((1, (0, 2), (), 3))
>>> to_tuple(x)
(1, 0, 2, (), 3)
?