11.產生器
Generator with for loop
生成器會依據yield一步一步往下走直遇到return丟出error為止
# with for loop
def generator_example():
a = 1
yield print(a) # 1
a += 1
yield print(a) # 2
return
for i in generator_example():
continue
# Output:
1
2
Generator with next, avoid StopIteration Error
手動執行生成器
# with next
def generator_example():
yield print(1)
yield print(2)
return
gen = generator_example()
gen.__next__() # 1
gen.__next__() # 2
gen.__next__() # raise StopIteration Error
使用例外接取錯誤
# avoid StopIteration Error
try:
gen.__next__()
except StopIteration:
pass # do nothing
Benefits - Memory Usage
生成器的好處 減少記憶體使用量
# 利用 list 迭代
range_num = 10
for i in [x*x for x in range(range_num)]:
pass# do something
# 利用 generator 迭代
for i in (x*x for x in range(range_num)):
pass# do something
Module
# A module is a file containing Python definitions and statements.
import re
import re as r
from re import findall
from re import *
Module - os
import os
# 顯示絕對路徑
os.path.abspath("session_1-ans.ipynb") # '/Users/felix/Python/session_1-ans.ipynb'
# 將多個字串組合為路徑
'/'.join(['path', 'result', 'a.csv']) # 'path/result/a.csv'
# 將多個字串組合為路徑
os.path.join('path', 'result', 'a.csv') # 'path/result/a.csv'
# 檢查某路徑/資料夾是否存在
os.path.exists("python\session_1-ans.ipynb") # False
Test5
Q1: 若某 k 位數的正整數,其所有位數數字的 k 次方和等於該數相等,則稱為阿姆斯壯數 (Armstrong
number)。 例如 1^3 + 5^3 + 3^3 = 153, 則 153 是一個阿姆斯壯數。
請創建一個 Generator 函式,找出 100 ~ 999 的所有三位數的阿姆斯壯數;
利用 yield 回傳數值,並且用多次呼叫的方式,依序列印出所找到的阿姆斯壯數。
for i in range(100,1000):
arr=str(i)
ans=int(arr[0])**3+int(arr[1])**3+int(arr[2])**3
if ans==i:
print(i)
def armstrong_number():
for i in range(100,1000):
ans=0
temp=i
while temp>0:
digit=temp%10
ans+=digit**3
temp//=10
if ans==i:
yield ans
a = armstrong_number()
try:
while(True):
print(a.__next__())
except StopIteration:
print("The End")