ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-tutor
python-tutor
Re: [Tutor] Splitting a number into even- and odd- numbered digits
by Barry Carroll other posts by this author
Apr 20 2006 9:56AM messages near this date
Re: [Tutor] Splitting a number into even- and odd- numbered digits | Re: [Tutor] Splitting a number into even- and odd- numbered digits
Greetings:

First of all, thanks to those who contributed suggestions.  

Unfortunately, my description was incomplete.
 
>  I am writing a function that accepts a string of decimal digits,
>  calculates a checksum and returns it as a single character string.
>  The first step in the calculation is to split the input into two
strings:
>  the even- and odd- numbered digits, respectively.  The least
significant
>  digit is defined as odd.
 
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.  
 
>  >>>>>>>
>  >>> s = '987654321'
>  >>> odd = ''
>  >>> for c in s[::-2]:
>  ...     odd = c + odd
>  ...
>  >>> s = s[:-1]
>  >>> even = ''
>  >>> for c in s[::-2]:
>  ...     even = c + even
>  ...
>  >>> odd
>  '97531'
>  >>> even
>  '8642'
>  >>>>>>>
 
Thanks again.  This is the most useful list I've ever found.

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

-Quarry worker's creed


_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Barry Carroll
Python
Barry Carroll
Barry Carroll
John Fouhy

Privacy Policy | Email Opt-out | Feedback | Syndication
© 2004 ActiveState, a division of Sophos All rights reserved