lang comparison: in-place algorithm for reversing a list in Perl, Python, Lisp

Rainer Weikusat rweikusat at mssgmbh.com
Thu Mar 1 15:39:25 CET 2012


Xah Lee <xahlee at gmail.com> writes:

[...]


> # perl
> # in-place algorithm for reversing a list.
>
> use strict;
> use Data::Dumper;
> use POSIX; # for “floor”
>
> my @listA = qw(a b c d e f g);
>
> my $listLength = scalar @listA;
>
> for ( my $i = 0; $i < floor($listLength/2); $i++ ) {
>   my $x = $listA[$i];
>   $listA[$i] = $listA[ $listLength - 1 - $i];
>   $listA[ $listLength - 1 - $i] = $x;
> }
>
> print Dumper(\@listA);

Better algorithm for that (expects an array reference as first
argument)

sub rev
{
    my $a = $_[0];
    my ($n0, $n1, $x);
    
    $n0 = 0;
    $n1 = $#$a;
    while ($n0 < $n1) {
	$x = $a->[$n0];
	$a->[$n0] = $a->[$n1];
	$a->[$n1] = $x;
	
	++$n0;
	--$n1;
    }
}

NB: The fact that a sufficiently sophisticated compiler might be able
to fix this automatically emphasizes the deficiencies of the original
attempt, it doesn't excuse them.



More information about the Python-list mailing list