[Tutor] newbie code review please!

Kent Johnson kent37 at tds.net
Sun Feb 3 22:35:08 CET 2008


Tyler Smith wrote:

> iflist = ifstring.replace('\n', ' ').split()

The replace is not needed, split() splits on any whitespace including 
newlines.

> # build hash of form (prefix1, prefix2): [word]
> word_hash = {}
> for i in range(len(iflist) - 2):
>     pr1 = iflist[i]
>     pr2 = iflist[i+1]
>     tv = iflist[i+2]
>     tk = (pr1, pr2)

or, tk = tuple(iflist[i:i+2])

>     if word_hash.has_key(tk) and tv not in word_hash[tk]:
>             word_hash[tk].append(tv)
>     else:
>         word_hash[tk] = [tv]

This could be done much more cleanly with a defaultdict that maps a pair 
to a set:

from collections import defaultdict
wordhash = defaultdict(set)
...then just
   wordhash[tk].add(tv)

> if word_hash.has_key((iflist[-2], iflist[-1])):
>     word_hash[(iflist[-2], iflist[-1])].append('\n')
> else:
>     word_hash[(iflist[-2], iflist[-1])] = ['\n']   

word_hash[(iflist[-2], iflist[-1])].add('\n')

> # generate new words from hash
> word_num = 0
> while w2 <> '\n' and word_num < word_max:
>     w1, w2 = w2, random.choice(word_hash[(w1, w2)])
>     print w2,
>     word_num += 1

or,
for word_num in range(word_max):
     w1, w2 = w2, random.choice(word_hash[(w1, w2)])
     print w2,
     if w2 == '\n':
         break

Kent


More information about the Tutor mailing list