3 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
在 def 中初始化列表并返回,并且范圍不應(yīng)包括原始num范圍,因此范圍將從 1 到 num,其中包括 1 但不包括原始num范圍,因此它將生成范圍從1到num-1
#Stores list of factors and first perfect number
x = 1
#Defines function for finding factors
def findfactors(num):
facs = []
for i in range(1, num):
if num % i == 0:
#Stores factor in facs
facs.append(i)
return facs
#Activates loop
while x < 1000:
#Finds factors of x and appends them to list
facs=findfactors(x)
#Finds sum of list
facsum = sum(facs)
#Makes decision based on sum of factors and original number
if facsum == x:
#Ouputs and increases x
print(x)
x+= 1
比從Python 中查找數(shù)字的所有因子的最有效方法是什么生成列表方法要快得多?
#Stores list of factors and first perfect number
x = 1
#Defines function for finding factors
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
#Activates loop
while x < 10000:
#Finds factors of x and appends them to list
facs=factors(x)
facs.remove(x) # remove original number as it is not required further
#Finds sum of list
facsum = sum(facs)
#Makes decision based on sum of factors and original number
if facsum == x:
#Ouputs and increases x
print(x)
x+= 1

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
這是您的邏輯的更簡(jiǎn)單實(shí)現(xiàn)。
x = 1
#Defines function for finding factors
def isperfectnum(num):
sum=0
#Creates for loop to find all factors of num
for i in range(1, num ):
if num % i == 0:
sum=sum+i
if sum==num:
return TRUE
else
return FALSE
#Activates loop
while x < 10000:
#Finds perfect numbers
if isperfectnum(x):
print(x)
x=x+1
添加回答
舉報(bào)