Thread Pythagorische Tripel (18 answers)
Opened by Ronnie at 2008-10-19 15:57

LanX-
 2008-10-29 15:48
#115819 #115819
User since
2008-07-15
1000 Artikel
BenutzerIn

user image
Hei Ronnie,

Ronnie+2008-10-19 13:57:41--
Zum Vergleich mal das selbe (als ListComprehension) in Python:
Code: (dl )
print [(a,b,c) for c in range(20) for b in range(c) for a in range(b) if c**2==a**2+b**2]

oder in Haskell (ghci):
Code: (dl )
1
2
let triangles = [ (a, b ,c) | c <- [1..], b <- [1..c], a <- [1..b], a^2+b^2==c^2 ]
take 10 triangles


Um deinen Bedürfnis nach ListComprehension nachzukommen anbei ein wenig Code wie man das nachbauen kann, letztendlich sind es nur verschachtelte Schleifen die eine Liste zurückgeben.

Was du in Python syntaktisch einsparst sind die Klammern, ob dadurch Python übersichtlicher wird als Perl is a Matter of Debate. Semantisch ist es IMHO das gleiche!


Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/perl

use Data::Dumper;

my $max=10;


### Straight forward


sub list (&){
    my $code_ref=shift;
    &$code_ref;
    return @_;
}


@x= list { for $c (1..10){ for $b (1..$c){ for $a (1..$b){
           push @_, [$c,$b,$a]  if $c**2 == $b**2 + $a**2;
    } } } };

print Dumper \@x;



### ist das pushen zu haesslich?

{
    my @list;

    sub gather (&){
        my $code_ref=shift;
        
        @list=();                          # KORRIGIERT:  danke Matthias W.
        &$code_ref;
        return @list;
    }

    sub take ($) {
        my $elem = shift;
        push @list, $elem;
        return;
    }
}



@x= gather {
    for $c (1..10){   for $b (1..$c){   for $a (1..$b){  if ( $c**2 == $b**2 + $a**2){
        take [$c,$b,$a]
    } } } }
};

print Dumper \@x;




### lazy evaluation ?




{
    my ($a,$b,$c)=(0,0,0);

    sub lazy {
        while ( $c++ < $max ) {
            while ( $b++ < $c ) {
                while ( $a++, $a %= $b ) {
                    return [$c,$b,$a] if $c**2 == $b**2 + $a**2;
                };
                # $a=0; # unnötig
            };
            $b=0;
        }
        $c=0;
        return;
    }
}





while ( $triple = lazy() ) {
    print Dumper $triple;
}

View full thread Pythagorische Tripel