2016-03-11 88 views
0

實現並測試下面的鏈接列表的方法蟒蛇鏈表FPGA實現

def intersection(self, rs): 
    """ 
    ------------------------------------------------------- 
    Copies only the values common to both the current list and rs 
    to a new list. Uses a looping algorithm. 
    ------------------------------------------------------- 
    Preconditions: 
     rs - another list (List) 
    Postconditions: 
     returns 
     new_list - contains one copy of values common to current list 
      and rs (List) 
     Current list and rs are unchanged. 
    ------------------------------------------------------- 
    """ 


class _ListNode: 

    def __init__(self, value, next_): 

     self._value = deepcopy(value) 
     self._next = next_ 
     return 


class List: 

    def __init__(self): 

     self._front = None 
     self._count = 0 
     return 

    def is_empty(self): 

     return self._front is None 

    def __len__(self): 

     return self._count 

    def insert(self, i, value): 

     if i < 0: 
      # negative index 
      i = self._count + i 

     n = 0 
     previous = None 
     current = self._front 


     while n < i and current is not None: 

      previous = current 
      current = current._next 
      n += 1 

     if previous is None: 
      self._front = _ListNode(value, self._front) 
     else: 

      previous._next = _ListNode(value, current) 
     self._count += 1 
     return 

這是我到目前爲止,我沒有現在該怎麼辦實施交會法

例子:

If List a contains: 
0, 2, 1, 3, 5, 7 


and List b contains: 
1, 1, 3, 3, 5, 5, 7, 7 


Then a.intersection(b) returns a List containing: 
7, 5, 3, 1 
+0

應該是什麼,如果列表中包含兩個'7's結果呢? – inspectorG4dget

+1

@ inspectorG4dget from後置條件,似乎結果列表將只包含一個相交值的副本 – brianSan

+0

one 7 @ inspectorG4dget – aleen1

回答

1

添加__contains__讓你的生活變得更輕鬆

def __contains__(self, val): 
    curr = self.front 
    while curr is not None: 
     if curr._value == val: return True 
     curr = curr._next 
    return False 


def intersection(self, rs): 
    answer = List() 
    curr = self.front 
    while curr is not None: 
     if curr._value in rs: answer.insert(-1, curr._value) 
    return answer 

路口遞歸:

def extend(self, rs): 
    curr = rs.front 
    while curr is not None: 
     self.insert(-1, curr._value) 

def intersection(self, rs): 
    if rs.front is None: return List() 
    answer = self.intersection(rs.front._next) 
    if rs.front._value in self: answer.insert(-1, rs.front._value) 
    return answer 
+0

非常感謝您,我有一個問題,我如何實現遞歸和輔助函數的交集方法。 – aleen1

+0

@ aleen1:檢查編輯 – inspectorG4dget

+0

當我運行函數我得到AttributeError:'列表'對象沒有屬性'交集' 這是我如何調用函數curr = [0,2,1,3,5,7 ] RS = [1,1,3,3,5,5,7,7] 答案= [] curr.intersection(RS) 交點(回答) 打印(回答) – aleen1