Python負数下付き

918 ワード

>>> class Fib(object):
	def __getitem__(self, n):
		if isinstance(n, int):
			a, b = 1, 1
			for x in range(n):
				a, b = b, a+b
			return a
		if isinstance(n, slice):
			start = n.start
			stop = n.stop
			if start is None:
				start = 0
			a, b = 1, 1
			L = []
			for x in range(stop):
				if x >= start:
					L.append(a)
				a, b = b, a+b
			return L

		
>>> Fib

>>> Fib()[8]
34
>>> Fib()[0:9]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> Fib()[:10]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> a = Fib()[0: 10]
>>> a
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> a[-10: -1]           #
[1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> a[-1]               #the last one's INDEX is -1
55
>>> a[-10]
1
>>> a[-9]
1
>>> a[-10: 0]
[]
>>> a[-10: ]         #
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]