List rotation
Michael Hoffman
m.h.3.9.1.without.dots.at.cam.ac.uk at example.com
Thu Sep 30 02:55:59 EDT 2004
M. Clift wrote:
> If the list ('a', 'd', 'b', 'a', 'd', 'c', 'b') was rotated once it would
> of course give('d', 'b', 'a' etc...
Yes. That is usually what people refer to as list rotation.
> What I'm looking for is that say if trans = 1, then the list would become
> ('b', 'a', 'c', 'b', 'a', 'd', 'c') .
It took me a second to figure out what you want. You want to increase
the characters' ordinal values by one along some rotated list:
adbadcb
bacbadc
so for trans=1, a->b, b->c, c->d, d->a. If I got that correct, than you
want something like this:
"""
def rotate_letters(items, trans=1, rotation="abcd"):
"""
alphabet can be a string or a list
"""
return [rotation[(rotation.index(item)+trans) % len(rotation)]
for item in items]
print rotate_letters("abcd")
print rotate_letters(('a', 'd', 'b', 'a', 'd', 'c', 'b'))
print rotate_letters(('a', 'd', 'b', 'a', 'd', 'c', 'b'), trans=3)
"""
which gives the output
"""
['b', 'c', 'd', 'a']
['b', 'a', 'c', 'b', 'a', 'd', 'c']
['d', 'c', 'a', 'd', 'c', 'b', 'a']
"""
and will throw IndexError if you give it input that's not in the
rotation alphabet.
For more efficiency, you'd want to precompute the result for each
character in the rotation alphabet and store the result in a translation
table to be used by str.translate(). That's left as an exercise to the
user. ;)
--
Michael Hoffman
More information about the Python-list
mailing list