[Tutor] Splitting a number into even- and odd- numbered digits

Carroll, Barry Barry.Carroll at psc.com
Thu Apr 20 19:01:41 CEST 2006


Greetings:

Unfortunately, my problem description was incomplete.  I forgot to
include two important requirements:

    1. the length of the input string is arbitrary,
    2. the order of the digits must be maintained.

I could not find a way to include these requirements in a single, simple
expression.  I decided to make an explicit test for string length, which
simplified matters. I came up with this:

>>>>>>>
>>> def odd_even(x):
...     if len(x) % 2 == 1:
...         return x[::2], x[1::2]
...     else:
...         return x[1::2], x[::2]

>>> odd_even('987654321')
('97531', '8642')

>>> odd_even('98765432')
('8642', '9753')
>>> 
>>>>>>>

which is an improvement, I think, on my original.  
 
Thanks to those who provided suggestions.  This is the most useful list
I've ever found.

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




More information about the Tutor mailing list