python - Sorting a "Tuple" by the second value (or by sum) -
my purpose make subroutine takes list of random 4-toops, sorts non-destructively sum of each toop largest smallest, , returns sorted list.
an example output should be:
---- random 4-toops: toop 1: (93 97 78 77); 345 toop 2: (-1 82 92 -45); 128 toop 3: (62 25 -31 -4); 52 toop 4: (-77 -86 18 36); -109 toop 5: (-72 -96 -83 -6); -257 ---- random 4-toops sorted sum: toop 1: (93 97 78 77); sum = 345 toop 2: (-1 82 92 -45); sum = 128 toop 3: (62 25 -31 -4); sum = 52 toop 4: (-77 -86 18 36); sum = -109 toop 5: (-72 -96 -83 -6); sum = -257
here python variation of code working:
def sort_random_4_toops_by_sum(toops): summit = 0 s = [] in toops: summit = 0 d in xrange(0,4): summit += i[d] s.append(summit) = zip(toops, s) sortedtog = sorted(together, key = lambda x: x[1],reverse=true) toops = [x[0] x in sortedtog] return toops
so stuck problem: in python, zipped sum list , tuples list together, , sorted second element in each tuple, sum. there equivalent function in perl can sort according second element of tuple? here attempt far.
sub sort_random_4_toops_by_sum { ( @sorted_toops,@sorted_toops2, @sorted_toops_sums, @sortedtoops3 ) = @_; @sorted_toops2 = map { [ $_, sum( @$_ ) ] } @sorted_toops; @sorted_toops_sums = reverse sort { $a->[1] <=> $b->[1] } @sorted_toops2; @sortedtoops3 = map { $_->[0] } @sorted_toops_sums; return \@sortedtoops3; }
it telling me this:
can't locate list/tuples.pm in @inc
the test code generate right output:
sub test_step_3 { $toops = gen_random_4_toops( 1, 100, 5 ); print "---- random 4-toops:\n"; $tn = 1; foreach ( @{ sort_random_4_toops_by_sum( @{$toops} ) } ) { print "toop $tn:\t(@{$_}); " . sum( @{$_} ) . "\n"; $tn++; } print "---- random 4-toops sorted sum:\n"; $sorted_toops = sort_random_4_toops_by_sum( @{$toops} ); $tn = 1; foreach ( @{$sorted_toops} ) { print "toop $tn:\t(@{$_}); sum = " . sum( @{$_} ) . "\n"; $tn++; } }
you've got way machinery there. since can't make lot of sense of code, i'm going work scratch. i'm going assume "4-tuples" array references of 4 elements each, because that's need be.
use list::util 'sum'; @tuples = generate_a_bunch_of_random_tuples(); # zip each tuple sum @tuples_with_sums = map { [ $_, sum(@$_) ] } @tuples; @sorted_with_sums = reverse sort { $a->[1] <=> $b->[1] } @tuples_with_sums; @sorted = map { $_->[0] } @sorted_with_sums;
it is, in fact, possible whole thing single statement in instance of schwartzian transform:
my @sorted = map { $_->[0] } reverse sort { $a->[1] <=> $b->[1] } map { [ $_, sum(@$_) ] } @tuples;
but wrote out long way sake of ease of understanding.
a "zip" (which can list::moreutils) of use if have multiple parallel lists. if every element of output list depends on 1 element of single input list, map
works — in fact, better.
Comments
Post a Comment