Hacker News new | comments | show | ask | jobs | submit login

> def Factorial(x): output = 1 for i in xrange(x): output = (i + 1) return output

Umm, did you mean:

    def factorial(x):
        output = 1
        for i in xrange(2, x):
            output *= i
        return output
Here are the perl versions. Such trivial examples are going to look the same in languages which share the same paradigms.

    use List::Util qw(reduce);

    # This is how I would write it.
    sub fact1 {
        my $num = shift;
        my $output = 1;
        $output *= $_ for (2 .. $num);
        return $output;
    }

    # Most people don't prefer inline loops and $_ variable, though
    # I don't see why not.
    sub fact2 {
        my $num = shift;
        my $output = 1;
        for my $i (2 .. $num) {
            $output *= $i;
        }
        return $output;
    }

    sub fact3 {
        my $num = shift;
        return reduce { $a * $b } 2..$num
    }



Based on the examples, I presume xrange(x) is every integer up to but not including x. ie 1..^$x in Perl 6, don't recall if that's the Perl 5 syntax or not.


> Based on the examples, I presume xrange(x) is every integer up to but not including x

Yes. That makes my Python example incorrect(should be xrange(2, num + 1))

> 1..^$x in Perl 6, don't recall if that's the Perl 5 syntax or not.

Perl 5 doesn have 1..^$x. I have always used 1..($n - 1) where I needed it - don't know if there is a better alternative.


> Yes. That makes my Python example incorrect(should be xrange(2, num + 1))

Or just xrange(num) and then, as in my original code, output *= num + 1. :-)


> Or just xrange(num) and then, as in my original code, output *= num + 1. :-)

HN ate your asterisk(it uses asterisk to mark italics), or something wrong with my chrome app for HN. In your post, I saw:

    def Factorial(x): output = 1 for i in xrange(x): output = (i + 1) return output




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: