user1140118
user1140118

Reputation: 61

Tuple and recursive list conversion

A recursive list is represented by a chain of pairs. The first element of each pair is an element in the list, while the second is a pair that represents the rest of the list. The second element of the final pair is None, which indicates that the list has ended. We can construct this structure using a nested tuple literal. Example:

(1, (2, (3, (4, None))))

So far, I've created a method that converts a tuple of values or the value None into a corresponding rlist. The method is called to_rlist(items). Example:

>>> to_rlist((1, (0, 2), (), 3))
(1, ((0, (2, None)), (None, (3, None))))

How do I write the inverse of to_rlist, a function that takes an rlist as input and returns the corresponding tuple? The method should be called to_tuple(parameter). Example of what should happen:

>>> x = to_rlist((1, (0, 2), (), 3)) 
>>> to_tuple(x)
(1, (0, 2), (), 3)

Note: The method to_rlist works as intended.

This is what I have so far:

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)

Which gives me the following result (which is incorrect):

>>> x = to_rlist((1, (0, 2), (), 3)) 
>>> to_tuple(x)
(1, 0, 2, (), 3)

How can I fix my method to return a nested tuple properly?

Upvotes: 5

Views: 8211

Answers (2)

This one worked for my HW ;)

def to_rlist(items):
    r = empty_rlist
    for i in items[::-1]:
        if is_tuple(i): r1 = to_rlist(i)
        else: r1 = i
        r = make_rlist(r1,r)
    return r

Upvotes: -1

wye.bee
wye.bee

Reputation: 716

def to_list(x):
    if x == None:
        return ()
    if type(x) != tuple:
        return x
    a, b = x
    return (to_list(a),) + to_list(b)

Upvotes: 5

Related Questions