2014-10-21 56 views
0

鑑於該類鏈接值插入一個鏈接,給定索引

class Link: 

    """A linked list. 

    >>> s = Link(1, Link(2, Link(3, Link(4)))) 
    >>> len(s) 
    4 
    >>> s[2] 
    3 
    >>> s 
    Link(1, Link(2, Link(3, Link(4)))) 
    """ 
    empty =() 

    def __init__(self, first, rest=empty): 
     self.first = first 
     self.rest = rest 

    def __getitem__(self, i): 
     if i == 0: 
      return self.first 
     else: 
      return self.rest[i-1] 

    def __len__(self): 
     return 1 + len(self.rest) 

    def __repr__(self): 
     if self.rest: 
      rest_str = ', ' + repr(self.rest) 
     else: 
      rest_str = '' 
     return 'Link({0}{1})'.format(self.first, rest_str) 

我怎麼會寫這樣的功能?

def insert(link, value, index): 
     """Insert a value into a Link at the given index. 

     >>> link = Link(1, Link(2, Link(3))) 
     >>> insert(link, 9001, 0) 
     >>> link 
     Link(9001, Link(1, Link(2, Link(3)))) 
     >>> insert(link, 100, 2) 
     >>> link 
     Link(9001, Link(1, Link(100, Link(2, Link(3))))) 
     >>> insert(link, 4, 5) 
     Index out of bounds 
     """ 
     "*** YOUR CODE HERE ***" 
+0

究竟是你想做些什麼? – mlwn 2014-10-21 23:34:45

+0

我試圖實現一個函數插入,它需要一個鏈接,一個值和一個索引,並將該值插入給定索引處的鏈接。假設鏈表已經至少有一個元素,並且它不返回任何東西;插入應改變鏈接列表 – 2014-10-21 23:39:06

+0

你做了什麼嘗試?你是否有特定的問題,或只是問如何做一個任務? – Parker 2014-10-21 23:50:12

回答

0

檢查下面有請:

class Link: 
    empty =() 
    def __init__(self, first, rest=empty): 
     self.first = first 
     self.rest = rest 

    def __getitem__(self, i): 
     if i == 0: 
      return self.first 
     else: 
      return self.rest[i-1] 

    def __len__(self): 
     return 1 + len(self.rest) 

    def __repr__(self): 
     if self.rest: 
      rest_str = ', ' + repr(self.rest) 
     else: 
      rest_str = '' 
     return 'Link({0}{1})'.format(self.first, rest_str) 

def insert(link, value, index): 
    if index >= link.__len__(): 
     print "Index out of bounds" 
    else: 
     if index == 0: 
      tmp = link.first 
      link.first = value 
      link.rest = Link(tmp, link.rest) 
     else: 
      insert(link.rest, value, index - 1) 

a = Link(1, Link(2, Link(3, Link(4)))) 
print a 
insert(a,23,0) 
print a 
insert(a,12,2) 
print a 
insert(a,3,6) 
print a 
insert(a,3,5) 
print a 
+0

的第一個元素來測試這個腳本,當你運行python時,只需從鏈接導入鏈接鍵入>>> >>> – mlwn 2014-10-22 00:39:31