Thursday 3 October 2013

Rookie mistake python loops and variable scope

While writing some simple python code I stumbled upon a rookie mistake which I appear to still be making so writing it down here to remind me.

Scope of variables is important in loops especially when using them to increment.

I was writing some code to work out if the product of two 3 digit numbers is a palindrome (not very elegant algorithm just brute forces it). Here is my original algorithm

a=100
b=100

numbers=[]

while a < 1000:
  while b < 1000:
    product=a*b
    print a, b, product
    if (product == int(str(product)[::-1])):
        print "palindrome"
        numbers.append(product)
    b+=1
  a+=1

From the output I noticed something strange the outer loop only went round once even though I thought I had incremented a after the inner loop.

Then it struck me I had defined b outside my while loop so it would not get reset upon next iteration of the outer loop and therefore the inner loop would not run again (and print something out). Therefore it looked like I was only looping once on the outer loop.
This could be proven by adding "print a" before incrementing a on the last line.

Moving "b=100" inside the outer loop solves the problem.

Working code looks like so
a=100
numbers=[]
while a < 1000:
  b=100
  while b < 1000:
    product=a*b
    print a, b, product
    if (product == int(str(product)[::-1])):
        print "palindrome"
        numbers.append(product)
    b+=1
  a+=1

Another alternative is to change the while loops to for loops.