List problem

Peter Hansen peter at engcorp.com
Fri Mar 29 17:16:38 EST 2002


Jon Cosby wrote:
> 
> Can anyone se why this is coming up empty in the "cols" list? I've tried
> something similar in the interpreter, and everything here looks right. For
> some reason, it isn't finding any matches here.
> 
> ########################################################################
> # WordSquare
> # Build word squares from initial word
> #
> 
> # Word dictionary
> dict = "c:\data\dict.txt"
> 
> firstword = input("Enter first word (enclosed in quotes): ")
> lword = len(firstword)
> words = []
> cols = []
> rows = []

Comments might help a lot.  For example, it's unclear what you are
trying to accomplish here, but it doesn't look quite right:

> f = open(dict, "r")
> for line in f.readlines():
>  if len(line[:-1]) == lword:
>   words.append(line[:-1])
> f.close()

That finds the line matching lword and appends it to words, I think,
which is another way of saying that every instance of lword in the
dict.txt file will be appended to the words list.  Strange...

> for i in range(lword):
>  cols.append([])
>  rows.append([])
> rows[0].append(firstword)

For every character in lword, append an empty list to the rows
and columns?  If that's what you want, you need range(len(lword))
since range() takes an integer.  Didn't you get an exception
here?

> # Generate an array of words with matching first letters
> for i in range(lword):

Same problem as above... use len() with range().

>  for word in words:
>    if word[0] == firstword[i]: # Matches not found
>    cols[i].append(word)
> 
> print len(words)
> print cols

Bad indentation here, but that's probably cosmetic.  Try not to 
use tabs when posting source, since many newsreaders screw them
up.  Use spaces instead.

Can you annotate your code so we know what you're trying to do?

-Peter



More information about the Python-list mailing list