0

For some reason, the x variable in the first for... loop changes from int to str after a single iteration through the code. I'm baffled as to why that must be, but each time I run this script, my set ends up being populated by strings consisting of hundreds of zeros.

In case anyone is curious, this is an attempt to solve Euler's question 4.

# A palindromic number reads the same both ways.
# The largest palindrome made from the product
# of two 2-digit numbers is 9009 = 91 99.
# Find the largest palindrome made from the product of two 3-digit numbers.

def palindrome():

    products = set()

    for x in xrange(700,999):
        for y in xrange(700,999):
            temp = x*y
            n = [x for x in str(temp)]
            if temp not in products:
                if len(n)%2 == 0:
                    half = len(n)/2
                    first = n[:half]
                    last = n[half:]
                    last.reverse()
                    if first == last:
                        products.add(temp)

    return products



if __name__ == "__main__":
    n = palindrome()
    print n
Zac Smith
  • 328
  • 1
  • 10
  • @InbarRose: the OP says he's doing [Project Euler's question #4](http://projecteuler.net/problem=4) – Kimvais Aug 08 '12 at 08:09

4 Answers4

7

In python 2.x, list comprehensions leak their variable to the enclosing scope. So your list comprehension [x for x in str(temp)] overwrites the value of x. But note that it will get set back to an int at the next iteration of the outer loop.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
3

It changes to a string because you assing a string to it:

        n = [x for x in str(temp)]

Mistakes like these are the reason why you should avoid one letter variables. That being said, I usually use _ as the throwaway variable in list comprehensions...

Kimvais
  • 38,306
  • 16
  • 108
  • 142
3

Don't use x inside the following list comprehension n = [x for x in str(temp)]. Just pick another variable name instead.

Maksim Skurydzin
  • 10,301
  • 8
  • 40
  • 53
-1
1    for x in xrange(700,999):
2        for y in xrange(700,999):
3            temp = x*y
4            n = [x for x in str(temp)]

after step#4, n = ['4', '9', '0', '0', '0', '0'], x = '0'

then for next step#3, temp='0'*701

zevolo
  • 66
  • 2