I looked several times across your code and if i get it right, your marking your rectangles with two different corner-markers. I'm sorry if my answer is more a comment to clarify your position then a really answer.
Answer-Part::
If your looking for an appropriate algorithm, consider a scan-line algorithm. I found an example here @SO for a "biggest rectangle solution".
My Question to you is, what are you really looking for?
- best way to solve the for-loop dilemma
- best language for your algorithm
- a faster algorithm to find rectangles
I must also point out, that Paul's and your solution produce different results, because Pauls assumes corners are marked by same values and you assume, that corners are marked through two different values!
I took the time and liberty to illustrate it with a ugly c&p script:
It compares both algorithm by creating a 2D-field and fills it with
string.lowercase chars and turns the corners to uppercase-chars.
from random import choice
from string import lowercase
from collections import defaultdict
from itertools import permutations
from copy import deepcopy
m,n = 20, 20
myarray = [[choice(lowercase) for x in xrange(m)] for y in xrange(n)]
def markcorners(i,j,i2,j2):
myarray[i][j] = myarray[i][j].upper()
myarray[i2][j] = myarray[i2][j].upper()
myarray[i2][j2] = myarray[i2][j2].upper()
myarray[i][j2] = myarray[i][j2].upper()
def printrect():
for row in myarray:
print ''.join(row)
print '*'*m
def paul_algo():
tally = defaultdict(list)
for i,row in enumerate(myarray):
for j,n in enumerate(row):
tally[n].append((i,j))
# look for rectangular quads in each list
for k,v in tally.items():
for quad in permutations(v,4):
# sort quad so that we can get rectangle corners
quad = sorted(quad)
(i1,j1),(i2,j2) = quad[0], quad[-1]
# slice out opposite corners to see if we have a rectangle
others = quad[1:3]
if [(i1,j2),(i2,j1)] == others:
markcorners(i1,j1,i2,j2)
def xavier_algo():
for i in xrange(m):
for j in xrange(n):
for i2 in xrange(i + 1, m):
for j2 in xrange(j + 1, n):
if myarray[i][j] == myarray[i2][j2] and myarray[i2][j] == myarray[i][j2]:
markcorners(i,j,i2,j2)
savearray = deepcopy(myarray)
printrect()
xavier_algo()
printrect()
myarray = deepcopy(savearray)
paul_algo()
printrect()