in reply to Algebraic Expansion of Binomials Using a Recursive Subroutine

I have refactored your code:
use warnings; use strict; # Get the input print "\nEnter the power: "; chomp(my $power = (<STDIN>)); if (($power =~ /\D/) or ($power == 0) or ($power > 9)) { die "Error: $power is not a positive integer less than 10"; } # Do the work my $result = binomial_power(1, $power, 1); # And print it out print "The result is: \n(x + y)^$power = $result\n"; sub binomial_power { my ($c, $xp, $yp) = @_; my $result = $c . "x^" . $xp . "y^" . ($yp - 1); $result =~ s/1x/x/g; $result =~ s/([xy])\^1/$1/g; $result =~ s/[xy]\^0//g; if ($xp > 0) { $result . " + " . binomial_power((($c * $xp)/$yp), ($xp-1), ($ +yp+1)); } else { return $result; } }
While I haven't eliminated the formatting regexes, I have combined a couple of them.

Please fix the spelling of "Binomals" in your title; it will help others find your code when searching.

UPDATE: changed input checking to reject power > 9, since our code does not support it.

Replies are listed 'Best First'.
Re^2: Algebraic Expansion of Binomials Using a Recursive Subroutine
by Jim (Curate) on Jul 31, 2011 at 04:03 UTC

    More refactoring…

    #!/usr/bin/perl use strict; use warnings; # Get the input... print "\nEnter the power (a positive integer from 1 through 33): "; chomp(my $power = (<STDIN>)); # Quietly end if there's no input... $power =~ m/\S/ or exit 1; # Validate the input... $power =~ m/^(?:[1-9]|[12][0-9]|3[0-3])$/ or die "$power is not a positive integer from 1 through 33\n"; # Expand the binomial... my $expansion = binomial_expansion(1, $power, 1); # ...and then print the result... print "(x + y)^$power = $expansion\n"; exit 0; sub binomial_expansion { my ($k, $x, $y) = @_; my $term = sprintf "%dx^%dy^%d", $k, $x, ($y - 1); $term =~ s/\b1(?=x)//; # Remove 1 from 1x $term =~ s/(?<=[xy])\^1(?!\d)//g; # Remove ^1 from x^1 and y^1 $term =~ s/[xy]\^0//; # Remove x^0 and y^0 return $x > 0 ? sprintf "%s + %s", $term, binomial_expansion(($k * $x) / $y, ($x - 1), ($y + 1)) : $term ; }
Re^2: Algebraic Expansion of Binomials Using a Recursive Subroutine
by Jim (Curate) on Jul 31, 2011 at 00:44 UTC

    Refactoring your refactoring just a tad…

    # Get the input... print "\nEnter the power (a positive integer from 1 through 9): "; chomp(my $power = (<STDIN>)); # Quietly end if there's no input... $power =~ m/\S/ or exit 1; # Validate the input... $power =~ m/^[1-9]$/ or die "$power is not a positive integer from 1 through 9\n";