python - Clear a list in a function each time it's run -
i'm kind of new programming. i'm trying write algorithm in python gives prime factors of number:
factors=[] def factor(n): in range(2,n+1): if n%i==0: factors.append(i) factor(int(n/i)) break return factors
it works, whenever run 'factor' function again, appends populated 'factors' list - how can list clear each time function 'factor' run?
declare local variable inside function. in code you're modifying global variable factors
every time call factor()
.
def factor(n, factors=none): factors = [] if factors none else factors in range(2, n + 1): if n%i==0 , not in factors: #checks duplicates factors.append(i) factor(int(n / i),factors) #pass factors list in recurive call break return factors factor(20) #returns [2, 5]
Comments
Post a Comment