[Python-de] 1,2,3,5,7,8,9 -> "1-3,5,7-9"

Christian Tanzer tanzer at swing.co.at
Fre Jun 18 15:59:50 CEST 2004


Versuch mal die Lösung:

def _ranges(s):
    if s:
        s.append (s[-1] + 2) ### sentinel to avoid cleanup after loop
        r = [s[0]]
        for v in s[1:]:
            d = v - r[-1]
            if d > 1:
                if len(r) > 2:
                    yield "%s-%s" % (r[0], r[-1])
                else:
                    for u in r:
                        yield str(u)
                r = [v]
            elif d == 1:
                r.append(v)

def collapsed_ranges(seq):
    s = list(seq)
    s.sort()
    return list(_ranges(s))

-- 
Christian Tanzer                                    http://www.c-tanzer.at/