![](/img/trans.png)
[英]Finding prime_factors that returns the prime factors of an integer as a list
[英]Finding list of numbers with 3 factors
我試圖輸出只有3個因素的數字。 我編寫了一個輸出所有因子的代碼,但無法輸出包含3個因子的數字。 例如,如果一個列表有1,5,6,7 ..它將輸出6 ..因為6具有三個因素:1、2和3 ..(本身)不是因素。 這是我到目前為止所擁有的:
def factors(n):
result = []
for i in range(1, n + 1):
if n % i == 0:
result.append(i)
return result
下面是一個簡單的示例,在其中循環一些數字並測試每個數字,以查看它是否恰好具有三個因素。 但這並不是特別有效...
#This will be your answers
results=[]
#Whatever you want your upper bound to be
highestValue=100
#Loop through up to your highest value
for eachVal in range(highestValue):
#If the length of the factor list is exactly 3, store the answer
if len(factors(eachVal))==3:
results.append(eachVal)
print(results)
編輯:當然,這是從代碼段中使用“因子”函數,因此請確保它位於同一模塊中,或者先導入它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.