我正在尝试制作一个完全可切片的斐波那契数列,但我被困在切片的阶梯特征上。这是我到目前为止的代码:
class Fib:
def __init__(self, start, end):
self.start = start
self.end = end
def _fib(self, index):
items = [0,1]
n = 2
while n <= index:
items.append(items[n-1]+items[n-2])
n += 1
return items
def __len__(self):
return self.end - self.start
def __reversed__(self):
items = self._fib(self.end)
return reversed(items)
def __count__(self, item):
items = self._fib(self.end)
return items.count(item)
def __getitem__(self, index):
if isinstance(index, slice):
return Fib(slice.start, slice.stop-1)
if index > len(self):
raise StopIteration
if index == 0:
return 0
if index == 1:
return 1
if index < 1:
return list(reversed(self._fib(self.end)))[abs(index)]
items = self._fib(index)
return items.pop()
它似乎可以与常规切片,反转和负数索引一起使用。但是,当我尝试使用诸如Fib(0,100)[:: 2]之类的步骤时,出现错误,我很难解释。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "fibonacci.py", line 22, in __getitem__
return Fib(slice.start, slice.stop-1)
TypeError: unsupported operand type(s) for -: 'member_descriptor' and 'int'
编辑: 我最终做了这个...
class Fib:
def __init__(self, start, end):
self.start = start
self.end = end
def _fib(self, index):
items = [0,1]
n = 2
while n <= index:
items.append(items[n-1]+items[n-2])
n += 1
return items
def __len__(self):
return self.end - self.start
def __reversed__(self):
items = self._fib(self.end)
return reversed(items)
def __count__(self, item):
items = self._fib(self.end)
return items.count(item)
def __getitem__(self, index):
if isinstance(index, slice):
_start, _stop, _step = (0, self.end, 1)
if index.start is not None:
_start = index.start
if index.stop is not None:
_stop = index.stop
if index.step is not None:
_step = index.step
abs_stop = _stop
abs_start = _start
if _stop < 0:
abs_stop = self.end + _stop
if _start < 0:
abs_start = self.end + _start
_n = max(abs_start, abs_stop) - 1
return self._fib(_n)[_start:_stop:_step]
if index > len(self):
raise StopIteration
if index == 0:
return 0
if index == 1:
return 1
if index < 1:
return list(reversed(self._fib(self.end)))[abs(index)]
items = self._fib(index)
return items.pop()
答案 0 :(得分:0)
应改为return Fib(index.start, index.stop-1)
。然后,由于切片中有None
(如果未提供),则应通过将index.start
替换为0
(如果长度为None
并用长度的index.stop
)来解决这一问题的顺序。