2

I am working on the Euler problems and found this code online for the third problem.

I used Python 3 to solve the third and fourth problems.

def lpf(c):  # largest_prime_factor
    i = 2
    while i * i <= c:
        if c % i:
            i += 1
        else:
            c //= i            # c // i returns the integer quotient of c/i 
    return c

I know that the // returns the integer quotient of a division, but what is happening when an equal sign is put just after it?

c //= i --> Is the integer quotient of c/i affected to the variable c?

Also, I am working on palindromes for problem 4 and I found this operator ::.

For example, here is code using it:

> s = str(12321)

> print(s == s[::-1])

Output : True  

(If the number is a palindrome, then output is True, else the output is False.)

Is the operator :: reading the string and changing it with an option? If so, how do you use it?

martineau
  • 119,623
  • 25
  • 170
  • 301
George Lashterg
  • 43
  • 1
  • 1
  • 8
  • `c // = i` does exactly what you stated `c // i returns the integer quotient of c/i ` its just shorthand the same as `c += i`, `c -= i`, `c %= i` etcetera are. As for `s[::-1]` this is reversing the string. – Pythonista Jun 18 '17 at 00:02

1 Answers1

4

If you read an operator like ??= with ?? a special operator, that usually (not always), can be replaced by:

c ??= e

into:

c = c ?? e

So the operation is done inplace. So here you have written:

c = c // i    # equivalent to c //= i

Note that sometimes inplace operations differ from their non-inplace counterparts. For instance for a list la += lb is not equal to la = la + lb. Since numerical values are immutable however, there is not much we can optimize here, so for numbers the above will (probably) always hold.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555