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[1])):
    for j in range(len(rows[2])):
        # ...Iterate to size - 1
        if firstword[0] + rows[1][i][0] + rows[2][j][0] in cols[0] \ #
Iterate to size - 1
        and firstword[1] + rows[1][i][1] + rows[2][j][1] in cols[1] \ #
Iterate to size - 1
        and firstword[2] + rows[1][i][2] + rows[2][j][2] in cols[2]: #
Iterate to size - 1
 # Iterate to size - 1
            w1 = rows[1][i]
            w2 = rows[2][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[1] in range(len(rows[1])):
    for i[2] in range(len(rows[2])):
        ...
            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")
for line in f.readlines():
 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[0] == firstword[i]:
   cols[i].append(word)

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

w1 = ""
w2 = ""

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

if w1 == "" or w2 == "":
 print "Solution not found"
else:
 print firstword
 print w1
 print w2

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






More information about the Python-list mailing list