Mapping into two lists

ivo at nospamAmaze.nl ivo at nospamAmaze.nl
Tue Sep 4 19:34:37 EDT 2001


Marcus Stojek <stojek at part-gmbh.de> wrote:
: Hi,

: I have a sorted list of int.  To generate an input file for
: a special software I have to split this list into two. Instead of
: explaining I'll give an example:

: List: [ 1, 3,4,5,6,7, 9, 11,12,13,14,15, 17]

: # start and end value of continuous list segment:
: Output list1: [3,7, 11,15] 
: # single values:
: Output list2: [1,9,17] 

The following code (no map() used) does what you want (if I understand
correctly what you want :)

l = [1, 3,4,5,6, 9, 11,12,13, 19, 21, 30,31, 77]

singles = []
ranges = []

cur = [ l[0] ]

for i in l[1:]:
    if i = cur[-1]+1:
        cur.append(i)
    else:
        if len(cur) == 1:
            singles.append(cur[0])
        else:
            ranges.extend([cur[0], cur[-1]])
        cur = [i]

if len(cur) == 1:
    singles.append(cur[0])
else:
    ranges.extend([cur[0], cur[-1]])


'cur' contains the current set you're working on, and it's initialized with
the first element of the original data. In each iteration, you check if the
new item 'extends the current set' or 'terminates the current set'. If it
does the latter, check the size of the set: if it's 1, it's a non-range,
else it's a range. Then you store them in the singles/ranges lists respectively.

At the end you have to check the reming set of the iteration. (you could
remove this check by doing 1 extra iteration by adding a guaranteed smaller
value to the list over which you iterate, i.e. "for i in l[:1] + [-1]",
or perhaps even [None], but that would ugly IMHO)

Btw, the algorithm will fail on an empty list.

Cheers,

	Ivo


-- 
Drs. I.R. van der Wijk                              -=-
Brouwersgracht 132                      Amaze Internet Services V.O.F.
1013 HA Amsterdam                                   -=-
Tel: +31-20-4688336                          Linux/Web/Zope/SQL
Fax: +31-20-4688337                           Network Solutions
Web:     http://www.amaze.nl/                    Consultancy
Email:   ivo at nospamAmaze.nl                         -=-




More information about the Python-list mailing list