# Iteration

Jon Cosby jcosby at mindspring.com
Mon Aug 26 19:03:28 CEST 2002

```I have a program that will write 3X3 word squares. A word square has columns
and rows that form words. For example,

AND
YOU
ERE

I want to extend this to any size, but I'm having problems with iteration.
Part of the code goes like this:

for i in range(len(rows)):
for j in range(len(rows)):
# ...Iterate to size - 1
if firstword + rows[i] + rows[j] in cols \ #
Iterate to size - 1
and firstword + rows[i] + rows[j] in cols \ #
Iterate to size - 1
and firstword + rows[i] + rows[j] in cols: #
Iterate to size - 1
# Iterate to size - 1
w1 = rows[i]
w2 = rows[j]
# Iterate to size - 1

"size" is the length of the first word, entered by the user (in this case,
three). How would I iterate the indices? How do you iterate a statement? An
array of indices might solve part of the problem, but what would be the
equivalent of

for i in range(len(rows)):
for i in range(len(rows)):
...
for i[s] in range(len(rows[s])):

The full code is below. Can this be modified for any size, or am I off
track?

######################################################################

size = 3

firstword = input("Enter a three letter word: ")
firstword = firstword.upper()

if len(firstword) != size:
raise ValueError, "Word must be three letters"

# Word dictionary
dict = "c:\data\dict.txt"
words = []

f = open(dict, "r")
if len(line[:-1]) == size:
words.append(line[:-1])
f.close()

cols = []  # columns
rows = []  # rows

# cols and rows are arrays of dim size
for i in range(size):
cols.append([])
rows.append([])

# Generate an array of words with matching first letters
for word in words:
for i in range(size):
if word == firstword[i]:
cols[i].append(word)

# Need code for any size
for i in range(len(cols)):
for j in range(len(cols)):
for k in range(len(cols)):
# ... Iterate to size - 1
if cols[i] + cols[j] + cols[k] in words:
rows.append(cols[i] + cols[j] + cols[k])
if cols[i] + cols[j] + cols[k] in words:
rows.append(cols[i] + cols[j] + cols[k])

w1 = ""
w2 = ""

# Need code for any size
for i in range(len(rows)):
for j in range(len(rows)):
# ...Iterate to size - 1
if firstword + rows[i] + rows[j] in cols \ # Iterate
and firstword + rows[i] + rows[j] in cols \ # Iterate
and firstword + rows[i] + rows[j] in cols: # Iterate
w1 = rows[i]
w2 = rows[j]
# Iterate

if w1 == "" or w2 == "":
else:
print firstword
print w1
print w2

######################################################################

```