2012-02-13 88 views
5

遞歸列表由一對對錶示。每一對中的第一個元素是列表中的一個元素,而第二個元素是一對代表列表的其餘部分。最後一對的第二個元素是None,表示列表已結束。我們可以使用嵌套元組文字構造這個結構。例如:元組和遞歸列表轉換

(1,(2,(3,(4,無))))

到目前爲止,我已經創建了一個方法,其將一個值的元組或值爲None的對應rlist。該方法被稱爲to_rlist(條目)。例如:

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

我怎樣寫to_rlist的倒數,其採用的rlist作爲輸入,並返回相應的元組的功能?該方法應該被調用to_tuple(參數)。應該發生什麼的示例:

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

注意:方法to_rlist按預期工作。

這是我到目前爲止有:

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) 

如何解決我的方法正確地返回一個嵌套的元組?

+1

遞歸列表是一個包含對自身的引用。 – wim 2012-02-13 01:22:39

+2

@wim它也可能意味着「根據自身定義的列表類型」,在這種情況下它適合。 (這也可能是作業使用的術語,它可以保留的另一個原因。) – millimoose 2012-02-13 01:26:26

+5

@ user1140118:堆棧溢出不是「爲我做的(部分)我的作業」網站。您應該自己開始使用該功能,併發布有關*特定*問題的問題。 – millimoose 2012-02-13 01:27:42

回答

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

1.使用'x是None'來比較單身人士2.使用'isinstance'進行類型檢查,以便代碼仍然適用於繼承類3.當您看到'homework'標記時,不要只發佈一個解決方案。幫助學生確定自己的工作需要改進哪些方面。 – wim 2012-02-13 02:01:12

+0

我試過解決方案,但只能連接元組(而不是「str」)到元組什麼是錯的? – Dejell 2014-01-08 05:51:23

-1

我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 
+5

什麼是empty_rlist和什麼是make_rlist? – Dejell 2014-01-08 06:13:39