When I run the python code below,
def main():
#print prime_factors(10)
print prime_factors(9)
def prime_factors(n, i=2, factors=[]):
if n==1:
return factors
if(n%i==0):
factors.append(i)
n = n/i
return prime_factors(n, i, factors)
else:
return prime_factors(n, i+1, factors)
if __name__ == '__main__':
main()
it returns the expected results, it returns the prime factors of 9:
[3, 3]
If I remove the comment from line 2 "print prime_factors(10)", something strange happens. For 10 everything is fine, but for 9 it does not only contain the prime factors of 9, but those of 10, as well:
[2, 5]
[2, 5, 3, 3]
If I call the function with the two optional arguments
def main():
print prime_factors(10, i=2, factors[])
print prime_factors(9, i=2, factors[])
everything works fine.
[2,5]
[3,3]
I can't figure out why. I suspect this is some issue with scopes, but I just don't understand it :-( Any help would be appreciated.