[2,3,4,7] --> "2-4,7" ?
BOCQUET Jean-Francois
jean-francois.bocquet at nospam.eurocontrol.int
Fri May 30 06:17:50 EDT 2003
hello,
just to notice that your problem is solved in perl with clean code :
sub display {
my ($prefix, $first, $last) = @_;
return "$prefix$first" if $last eq $first;
return "$prefix$first-$last";
}
my @names = qw(6 7 mx8 mx09 mx10 8 9 10 foo);
my @result;
my ($prefix, $integer) = (shift @names) =~ m/(\D*)(\d*)/;
my $last = $integer;
while (my ($new_prefix, $new_integer) = (shift @names) =~ m/(\D*)(\d*)/) {
if ($new_prefix eq $prefix and $new_integer == $last + 1) {
$last += 1;
} else {
push @result, display ($prefix, $integer, $last);
$prefix = $new_prefix;
$integer = $last = $new_integer;
}
last unless @names;
}
push @result, display ($prefix, $integer, $last);
print join (',', @result) . "\n";
or can be solved in a concise way (perhaps someone can do better) :
my @o;
@result = grep {if ($_->[0] eq $o[0] and $_->[1] == $o[2]+1) {$o[2]++;0}
else {($_, at o)=(display(@o),@$_);1}} map {m/(\D*)(\d*)/;[$1,$2, $2]} @names;
push @result, display(@o);shift @result;
"George Young" <gry at ll.mit.edu> wrote in message
news:pan.2003.05.29.19.11.15.218757 at ll.mit.edu...
> [python 2.3a1]
> I have a list of "names" like:
> ['6','7','mx8','mx09','mx10','8','9','10','foo']
> which needs for concise and clear display to become a string like:
>
> "6-7,mx8-10,8-10,foo"
>
> I.e., a name is an integer or an alphabetic prefix possibly followed
> by an integer. The display must compress each set of succesive names
> having the same (possibly null) prefix and sequential integers. The
> original order of names must be preserved.
>
> I (hesitantly) post the following code that works, but makes me cringe
> anytime I see it, for it's clumsy unreadableness. Can someone with
> a fresh mind see a clear and concise way to make my clear and concise
> name display?
>
>
> names = ['6','7','mx8','mx09','mx10','8','9','10','foo']
> groups = []
> import re
>
> def collapse(x,y):
> if x and x[-1][1] and y[1] and x[-1][0] == y[0] and int(x[-1][2]) ==
(int(y[2])-1): x[-1][2] = y[2]
> return x
> else:
> x.append(y)
> return x
>
> groups = []
> for n in names:
> r = re.compile('\d*$').search(n)
> groups.append([n[0:r.start()], n[r.start():r.end()],
n[r.start():r.end()]])
>
> r = reduce(collapse, groups, [])
> s=[]
> for i in r:
> if i[1] == i[2]:
> n=i[1]
> else:
> n=i[1] + '-' + i[2]
> s.append(i[0] + n)
>
> print ','.join(s)
>
More information about the Python-list
mailing list