NuclearVision wrotei still don't get the n/=d., which probably means n=d/n,
No.
In Python the two following expressions are equivalent:
• a (op)= b
• a = a (op) b
Thus n /= d is equivalent to n = n/d.
NuclearVision wrotebut we can't change the value of n
The function is not changing the value of n, it's changing the value of
a copy of n. What do you think the output of the following code will be?
def foo(n):
n = 5
return n
n = 10
foo(n)
print(n)
Answer: 10.
This is because the variable n is never passed to function foo. Instead a copy of n, containing the same value, is sent.
Note that this behavior is specific to Python, and you cannot make the same assumptions about other languages. You can learn more by reading the Wikipedia article on
Evaluation Strategy.
Also note that Python has a somewhat complex evaluation strategy (similar to the ones used by Java or - surprise - Ruby). You can
read more about it here.
Understanding the code better
My favorite way of understanding a piece of code I cannot immediately understand, is to add print() calls. So I modified the code to be like this:
def pf(n):
d = 2
primes = []
while (n > 1):
while (n % d == 0):
print d, n, primes
primes.append(d)
n /= d
d = d + 1
return primes
(Notice the print call on line 6)
You can now experiment with different input inside the python interpreter. I'm assuming you work on Windows, and I don't know how to launch the interpreter there, so maybe somebody else can help you with that. In any case, here are some sample outputs:
>>> pf(24)
2 24 []
2 12 [2]
2 6 [2, 2]
3 3 [2, 2, 2]
[2, 2, 2, 3]
>>> pf(38)
2 38 []
19 19 [2]
[2, 19]
>>> pf(236)
2 236 []
2 118 [2]
59 59 [2, 2]
[2, 2, 59]