Iteration

Frank Buss fb at frank-buss.de
Tue Aug 27 14:44:42 EDT 2002


"Jon Cosby" <jcosby at mindspring.com> 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:
    words.append(line)
if len(words) == 0:
  print 'No words found with', size, 'characters'
  sys.exit()

# 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)
  else:
    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]
    print

# search all squares
iterate(0)

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 frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de



More information about the Python-list mailing list