我需要創建一個函式,該函式將作為生成器連續回傳,即每個值與作為輸入給出的所有值的平均值之差的平方。
該函式必須
A) 接受未定義數量的引數
B) 是一個生成器函式
這些值將是整數。
要計算所有值的平均值,我可以匯入統計資訊。
你有什么想法嗎?
我嘗試撰寫的代碼:
import statistics
def squares(*args):
for i in args:
a=(args-av)**2
yield a
lst=[]
count = int(input("Give the amount of numbers: "))
for i in range (0,count):
ele=int(input())
lst.append(ele)
av=statistics.mean(lst)
for i in squares(*lst):
print(i)
uj5u.com熱心網友回復:
腳本中唯一的錯誤來自在計算中使用args而不是i:
import statistics
def squares(*args):
for i in args:
a=(i-av)**2 # <-- There.
yield a
lst=[]
count = int(input("Give the amount of numbers: "))
for i in range (0,count):
ele=int(input())
lst.append(ele)
av=statistics.mean(lst)
for i in squares(*lst):
print(i)
我還建議使用def squares(av, *args)只是這樣你av就不會從某個地方出來。然后,您必須將最后一行修改為for i in squares(av, *lst). 否則一切看起來都不錯!
我的建議:
import statistics
def squares(average, *items):
for item in items:
yield (item - average)**2
lst = []
count = int(input("Give the amount of numbers: "))
for _ in range(count):
item = int(input())
lst.append(item)
average = statistics.mean(lst)
for square in squares(average, *lst):
print(square)
uj5u.com熱心網友回復:
您的av變數應該在生成器函式內計算:
def squares(*args):
av = sum(args)/len(args)
for a in args:
yield (a-av)**2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/384554.html
