dave <[EMAIL PROTECTED]> writes:

> Hello,
>
> I made a function that takes a word list (one word per line, text
> file) and searches for all the words in the list that are 'shifts' of
> eachother.  'abc' shifted 1 is 'bcd'
>
> Please take a look and tell me if this is a viable solution.
>
> def shift(word, amt):
>       ans = ''
>       for letter in word:
>               ans = ans + chr((ord(letter) - ord('a') + amt) % 26 + ord('a'))
>       return ans

In Python, if you want to build a string from lots of parts you can
use ''.join(parts).  I think it is considered more efficient.


>
> def fileshift(x):
>       fin = open(x)
>       d = {}
>       for line in fin:
>               d[line.strip()] = [1]
>               for i in range(1, 26):
>                       ite = shift(line.strip(), i)
>                       if ite in d:
>                               print ite
>


You could write:

       line = line.strip()

after your for line in fin: statement, rather than strip the line twice.

Let me suggest a different solution base on the str.translate() method

from string import lowercase, maketrans

shifted_lowercase = lowercase[1:] +lowercase[0]
table = string.maketrans(lowercase, shifted_lowercase)

def shift1(line):
    return line.translate(table)

def fileshift(path):
    lines = set()
    for line in open(path):
        lines.add(line)
        for i in xrange(25):
            line = shift1(line)
            if line in lines:
                print line

(untested)

-- 
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to