Frank Buss fb at
Tue Aug 27 14:44:42 EDT 2002

"Jon Cosby" <jcosby at> wrote:

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

Looks very complicated. I'm a Python newbie (not a programmer newbie :-), 
so perhaps someone can correct my code, if it is not Python-like, but you 
can write it with a recursive function:

from string import strip
import random
import sys

# set size
global size, current, words
size = 3

# read words
words = []
for line in open('dict.txt', 'r').readlines():
  line = strip(line)
  if len(line) == size:
if len(words) == 0:
  print 'No words found with', size, 'characters'

# init globals  
current = size * [[]]
testWord = size * ' '

# recursive test function
def iterate(index):
  if index < size:
    for word in words:
      current[index] = word
      iterate(index + 1)
    for column in range(0, size):
      word = ''
      for row in range(0, size):
        word += current[row][column]
      if word not in words: return
    print "solution found:"
    for row in range(0, size): print current[row]

# search all squares

This code prints all possible squares of a given size. But it could be 
very time consuming: numberOfWords^size. If you have 1000 words and size 4 
it would take 1,000,000,000,000 iterations, so it would take 11 days, if 
your computer can check 1 squares per second. But it will be much faster, 
if you set the first word.

Frank Buß, fb at,

More information about the Python-list mailing list