鉴于课程链接,
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 :(得分: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