word shifts

George Sakkis george.sakkis at gmail.com
Mon May 5 23:22:49 EDT 2008


On May 5, 11:02 pm, dave <squareswallo... at yahoo.com> wrote:
> On 2008-05-04 01:10:40 -0600, Arnaud Delobelle <arno... at googlemail.com> said:
>
>
>
> > dave <squareswallo... at invalid.com> 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.
>
> what would be the best way to write a "ans = ans + chr" into a
> ''.join(parts) ??

Well if you do it once, that would be simply "ans += chr". Arnaud was
referring to the case where you do it in a loop, like in your snippet.
A direct translation to use ''.join would be:

ans = ''.join(chr((ord(letter) - ord('a') + amt) % 26 + ord('a'))
              for letter in word)

Of course it is simpler and more efficient if you factor out of the
loop the subexpressions that don't need to be recomputed:

ord_a = ord('a')
shift = ord_a - amt
ans = ''.join(chr((ord(letter) - shift) % 26 + ord_a)
              for letter in word)

George



More information about the Python-list mailing list