![](/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.