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. start the for loop from t = 2. I didnt find any way to do it. So I deleted "t" at the end. 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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.