Discuss / Python / __getitem__加入对切片step参数的支持

__getitem__加入对切片step参数的支持

Topic source

4Neutrino

#1 Created at ... [Delete] [Delete and Lock User]
class Fib(object):
    def __getitem__(self, n):
        if isinstance(n, int): # n是索引
            a, b = 1, 1
            for x in range(n):
                a, b = b, a + b
            return a
        if isinstance(n, slice): # n是切片
            start, stop, step = self.__check_slice(n)

            s = set([])
            curr = start
            while curr < stop if step > 0 else (curr >= 0 if stop is None else curr > stop and stop >= 0):
                s.add(curr)
                curr += step

            l = []
            if len(s) > 0:
                a, b = 1, 1
                m  = max(start, stop) if stop is not None else start
                for n in range(m + 1):
                    if n in s:
                        if step > 0:
                            l.append(a)
                        else:
                            l.insert(0, a)
                    a, b = b, a + b
            return l

    def __check_slice(self, n):
        start = n.start
        stop = n.stop
        step = n.step

        if step == 0:
            raise ValueError('step should not be zero')
        if step is None:
            step = 1
        if start is None:
            if step > 0:
                start = 0
            else:
                raise ValueError('start should not be None while step is negative')
        if stop is None and step > 0:
            raise ValueError('stop should not be None while step is positive')

        return (start, stop, step)


f = Fib()
print(['(%s)%s' % (i, n) for i, n in enumerate(f[:17])])
print(f[16:1:-3])
print(f[16::-3])
print(f[3:9:2])
print(f[:9:3])
print(f[:9:])

  • 1

Reply