迭代器構造斐波那契數列

2022-09-18 12:12:16 字數 2019 閱讀 3695

# class fei(object):

# def __init__(self,n):

# self.n = n

# self.num1 = 0

# self.num2 = 1

# self.current = 0

## def __iter__(self):

# return self

## def __next__(self):

# if self.current < self.n:

# num = self.num1

# self.num1,self.num2 = self.num2,self.num1+self.num2

# self.current += 1

# return num

# else:

# raise stopiteration

## if __name__ == '__main__':

# fei = fei(20)

# while true:

# try:

# print(next(fei),end=" ")

# except stopiteration:

# break

class fei(object):

def __init__(self,n):

self.num1 = 0 # 第乙個初始值

self.num2 = 1 # 第二個初始值

self.current = 0 # 代表下標,記錄位置

self.n = n # 構造長度為n的斐波那契數列

def __iter__(self):

"""返回自身"""

return self

def __next__(self):

"""獲取下乙個位置元素"""

if self.current < self.n:

num = self.num1 # 用乙個變數臨時儲存初始值0

self.num1,self.num2 = self.num2, self.num1+self.num2 # 構造斐波那契數列下乙個值

self.current += 1 # 構造一次位置變更一次

return num

else:

raise stopiteration # 超出長度跑出停止迭代異常

if __name__ == '__main__':

fei = fei(10)

for i in fei:

print(i,end=" ")

# def fei(n):

# num1,num2 = 0,1

# current = 0

# while current < n:

# num = num1

# num1,num2 = num2,num1+num2

# current += 1

# yield num

# else:

# raise stopiteration

## if __name__ == '__main__':

# f = fei(10)

# for i in f:

# print(i)

# print(list(f))

# while true:

# try:

# print(next(f),end=" ")

# except stopiteration:

# break

迭代器實現斐波那契數列

class fibiterator object 斐波那契數列迭代器 def init self,n param n int,指明生成數列的前n個數 self.n n current用來儲存當前生成到數列中的第幾個數了 self.current 0 num1用來儲存前前乙個數,初始值為數列中的第乙個...

python迭代器實現斐波那契數列

什麼是迭代器,作用是什麼。迭代器實現斐波那契數列。1.概念 從容器中取資料的工具就是迭代器 游標 2.作用 可以節省大量的記憶體空間 0,1,1,2,3,5,8,13,21,34 初始值 a 0 b 1 游標 當前數值 index 0 斐波那契數列最大數量為 num num根據需求建立乙個類 cla...

Python迭代器實現斐波那契數列

python 處理 for 迴圈時,首先會呼叫 something.iter 返回 something 對應的迭代器 假設叫 it 而後,for 迴圈會呼叫 it.next 獲取迭代器的下乙個元素,並賦值給 x,然後執行迴圈體 執行完後,for 迴圈會繼續呼叫 it.next 獲取迭代器的下乙個元素...