Skip to content Skip to sidebar Skip to footer

Confused About A Variable Assignment (python)

For a task on ProjectEuler I've written code that uses brute force to find the longest chain of primes below 100 that add up to a prime, and the code does give the correct results.

Solution 1:

seq = chain creates another reference to the same chain list. You then print that list, but the loop doesn't stop.

You continue to expand chain, and since seq is just a reference to that list, you'll see those changes once the loop has ended. During the remaining for loop iterations chain / seq continues to change, but the if condition is no longer met so you don't see these changes take place.

You continue to expand chain here:

chain += [primes[secnum]]

This uses augmented assignment; it doesn't create a new list but extends the existing list. It is equivalent to chain.extend(primes[secnum]).

You can fix this by creating a copy of chain to store in seq:

seq = chain[:]

Solution 2:

In python you can use + operator to join two lists together. So [1] + [2] will yield [1,2]

    chain += [primes[secnum]]
    if len(chain) > record and sum(chain) in primes:
        record = len(chain)
        seq = chain
        printseq

chain variable is getting bigger by += operator which is joining chain ( a list ) to another list . So it will get bigger and when you print seq, because seq is equal to chain now, you get the latest result.

Post a Comment for "Confused About A Variable Assignment (python)"