[英]How can i find Prime factors
def fi_da_prfac(var):
fac = []
prfac = []
z = range(2, (var/2)+1)
z.append(var)
for t in z:
if var == t:
prfac.append(t)
z = range(2, (var/2)+1)
z.append(var)
break
else:
if var % int(t) == 0:
prfac.append(t)
var = var/t
del z
z = range(2, (var/2)+1)
z.append(var)
del t
return prfac
I am a beginner at coding.我是编码初学者。 I am trying to write a code to find the Prime factorisation of a given number.
我正在尝试编写代码来查找给定数字的质数分解。 If we analyze the code, what I want to do is that if I find a factor, I want to start the for loop again ie.
如果我们分析代码,我想要做的是,如果我找到一个因素,我想再次启动for循环即。 start the for loop from t = 2. I didnt find any way to do it.
从 t = 2 开始 for 循环。我没有找到任何方法来做到这一点。 So I deleted "t" at the end.
所以我最后删除了“t”。 However the code isnt giving the desired output.
然而,代码没有给出所需的输出。 I tried a lot to debug it but couldn't.
我尝试了很多来调试它,但不能。 Please help
请帮忙
The fundamental piece to the puzzle you are missing is the yield operator, this makes the function act as a generator and keeps its place when running through a loop.您所缺少的难题的基本部分是 yield 运算符,这使函数充当生成器并在运行循环时保持其位置。 A key thing to note however is the output will be a generator object which must be looped through to extract your desired output.
然而,需要注意的关键是输出将是一个生成器对象,必须循环遍历以提取所需的输出。
Your example:你的例子:
import math
def fi_da_prfac(var):
z = range(2, math.ceil(var/2)+1)
z.append(var)
for t in z:
if var % int(t) == 0:
yield t
prfac = yield_eg(15)
[fac for fac in prfac]
This is a nice problem for learning how to code, however as others of mentioned there are more concise pre-made functions to achieve this if you need.这是学习如何编码的一个很好的问题,但是正如其他人提到的,如果您需要,可以使用更简洁的预制函数来实现这一点。
Usherwood厄舍伍德
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.