Skip to content

Instantly share code, notes, and snippets.

@tarunbod
Last active March 4, 2024 03:57
Show Gist options
  • Save tarunbod/217a779ea21d6cfbe6ce to your computer and use it in GitHub Desktop.
Save tarunbod/217a779ea21d6cfbe6ce to your computer and use it in GitHub Desktop.
Binomial Expansion in Python
#!C:/Python34/python.exe
import sys, re
from math import pow
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
def nCr(n, r):
return factorial(n) / (factorial(r) * factorial(n - r))
def pascal(row, num):
return nCr(row, num - 1)
def pascal_for_row(row):
row_nums = list()
for i in range(1, row + 2):
row_nums.append(pascal(row, i))
return row_nums
BINOMIAL_REGEX = "\\((?:(\\d+)([a-zA-Z])(?:\\^(\\d+)?)?)(\\+|\\-)(?:(\\d+)([a-zA-Z])(?:\\^(\\d+)?)?)\\)(?:\\^(\\d+))"
binomial = input("Enter a binomial to expand: ").replace(" ", "")
match = re.search(BINOMIAL_REGEX, binomial)
if match is None:
print("Invalid Binomial.")
sys.exit(0)
first_coeff = int(match.group(1))
first_var = match.group(2)
first_exp = int(match.group(3) if match.group(3) else 1)
add = match.group(4) == '+'
second_coeff = int(match.group(5))
second_var = match.group(6)
second_exp = int(match.group(7) if match.group(7) else 1)
power = int(match.group(8))
pascal_row = pascal_for_row(power)
expanded = ""
for i in range(0, len(pascal_row)):
if i is len(pascal_row) - 1:
expanded += str(int(pow(second_coeff, i)) * pascal_row[i]) + str(second_var) + "^" + str(i) + " "
elif i is 0:
expanded += str(int(pow(first_coeff, power - i)) * pascal_row[i]) + str(first_var) + "^" + str(power - i) + " "
else:
expanded += str(int(pow(first_coeff, power - i)) * int(pow(second_coeff, i)) * pascal_row[i]) + str(first_var)
if power - i is not 1:
expanded += "^" + str(power - i) + "*"
expanded += str(second_var) + " "
if i is not 1:
expanded += "^" + str(i) + " "
if i is not len(pascal_row) - 1:
expanded += ("+ " if add else "- ")
print(expanded)
/**
* APCS-Programs
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Tarun Boddupalli
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package me.tarunb.apcs;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BinomialExpansion {
public static final Pattern BINOMIAL_REGEX = Pattern.compile("\\((?:(\\d+)([a-zA-Z])(?:\\^(\\d+)?)?)(\\+|\\-)(?:(\\d+)([a-zA-Z])(?:\\^(\\d+)?)?)\\)(?:\\^(\\d+))?");
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a binomial to expand: ");
String binomial = scanner.nextLine().replaceAll(" ", "");
Matcher matcher = BINOMIAL_REGEX.matcher(binomial);
if (!matcher.matches()) {
System.out.println("Invalid binomial.");
System.exit(0);
}
int firstCoeff = Integer.parseInt(matcher.group(1));
char firstVar = matcher.group(2).charAt(0);
int firstExp = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 1;
boolean add = matcher.group(4).charAt(0) == '+';
int secondCoeff = Integer.parseInt(matcher.group(5));
char secondVar = matcher.group(6).charAt(0);
int secondExp = matcher.group(7) != null ? Integer.parseInt(matcher.group(7)) : 1;
int power = matcher.group(8) != null ? Integer.parseInt(matcher.group(8)) : 1;
System.out.format("Original: (%d%s^%d %s %d%s^%d)^%d\n", firstCoeff, firstVar, firstExp, (add ? '+' : '-'), secondCoeff, secondVar, secondExp, power);
int[] pascalRow = pascal(power);
StringBuilder expanded = new StringBuilder();
for (int i = 0; i < pascalRow.length; i++) {
if (i == pascalRow.length - 1) {
expanded.append((int) Math.pow(secondCoeff, i) * pascalRow[i]).append(secondVar).append("^").append(i).append(" ");
} else if (i == 0) {
expanded.append((int) Math.pow(firstCoeff, power - i) * pascalRow[i]).append(firstVar).append("^").append(power - i).append(" ");
} else {
expanded.append((int) Math.pow(firstCoeff, power - i) * (int) Math.pow(secondCoeff, i) * pascalRow[i]).append(firstVar);
if (power - i != 1) {
expanded.append("^").append(power - i).append("*");
}/* else {
expanded.append(" ");
}*/
expanded.append(secondVar).append(" ");
if (i != 1) {
expanded.append("^").append(i).append(" ");
}/* else {
expanded.append(" ");
}*/
}
if (i != pascalRow.length - 1) expanded.append(add ? "+ " : "- ");
}
System.out.println(expanded.toString());
/*System.out.print("Enter the row: ");
long rows = scanner.nextInt();
scanner.close();
for (long i = 0; i < rows; i++) {
System.out.format("%" + (rows - i) * 2 + "s", "");
for (long j = 1; j <= i + 1; j++) {
System.out.format("%4d", pascal(i, j));
}
System.out.println();
}
System.out.println("\n");*/
}
public static long factorial(long n) {
long total = 1;
for (long i = 2; i <= n; i++) {
total *= i;
}
return total;
}
public static long nCr(long n, long r) {
return factorial(n) / (factorial(n - r) * factorial(r));
}
public static long pascal(long row, long num) {
return nCr(row, num - 1);
}
public static int[] pascal(int row) {
int[] nums = new int[row + 1];
for (int i = 1; i <= row + 1; i++) {
nums[i - 1] = (int) pascal(row, i);
}
return nums;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment