千里之行,始于足下
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 = n.start
stop = n.stop
step = n.step
if start is None:
start = 0
if step is None:
step = 1
a, b = 0, 1
L = []
for x in range(start + 1):
a, b = b, a + b
if x == start:
L.append(a)
next = start + step
for i in range(next, stop, step):
for x in range(step):
a, b = b, a + b
L.append(a)
return L
f = Fib()
print(f[5])
print(f[0:5])
print(f[:10])
print(f[0:10:2])
结果 :
8
[1, 1, 2, 3, 5]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
[1, 2, 5, 13, 34]学习一下getitem的操作 我们定义了一种数据结构,并对不同操作写了不同处理
实现的是一个斐波那契数组,可根据索引取值也可使用切片取值
如果是根据索引取值的话就通过for循环,得到该索引的值,返回
如果是切片的话,首先弄清楚起始索引,结束索引和步长,然后使用for循环生成数组,按条件添加,返回
class MyQueue:
def __init__(self):
self.stack_1 = []
self.stack_2 = []
def push(self, element):
while self.stack_1:
self.stack_2.append(self.stack_1.pop())
self.stack_1.append(element)
while self.stack_2:
self.stack_1.append(self.stack_2.pop())
def top(self):
if self.stack_1:
return self.stack_1[-1]
def pop(self):
return self.stack_1.pop()
queue = MyQueue()
queue.push(1)
print(queue.pop())
queue.push(2)
queue.push(3)
print(queue.top())
print(queue.pop())
结果:1
2
2我们实现一个队列结构,队列是先进先出的,数组的pop是出最后一个数,是先进后出的,所以定义两个数组是用来颠倒方向的,这样先添加的数在最后面,pop的就是最先添加的数