word shifts

Arnaud Delobelle arnodel at googlemail.com
Tue May 6 02:06:02 EDT 2008


George Sakkis <george.sakkis at gmail.com> writes:

> 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

Or keep the same layout as your original effort, but build a list of
chars instead of a string, then join them all at the end.

def shift(word, amt):
    shifted = ''
    ord_a = ord('a')
    shift = ord_a - amt
    for letter in word:
        shifted.append(chr((ord(letter) - shift) % 26 + ord_a))
    return ''.join(shifted)

(Which exactly the same as George's snippet, except that the generator
expression is unwound)

-- 
Arnaud



More information about the Python-list mailing list