Skip to main content
2 of 6
edited title

Pascal's Triangle Generator - Code improvement to make it more concise

**Hello, Everybody.
Recently attempted coding pascals triangle in python. Function:
For those that are unaware, pascals triangle is a simple and effective way to expand a set of brackets in the form (a + b)n. In my code the user is asked an input for what order(n) they want and it outputs pascals triangle. The Code:.
I added in comments to help your understand my reasoning.

def get_super(x):  # function to get superscript char.
    normal = "0123456789"
    super_s = "⁰¹²³⁴⁵⁶⁷⁸⁹"
    res = x.maketrans(''.join(normal), ''.join(super_s))
    return x.translate(res)
# the history_variable will be the variable returned when function is called. It will contain each co-efficient of every row.
# the number of rows that the history_variable returns is provided by parameters(num)
# I created save_variable as a variable I can use to store the previous row because I need it to create the next row.
# current_variable is a variable that will contain the current row being made.
def basic_pascals(num):
    history_variable = [[1], [1, 1]]
    save_variable = [1, 1]
    current_variable = []
    amount = 0
# if the number given is 0 just return 1 as that is the first row.
    if num == 0:
        return([1])
# if the number given is 1 return [1, 1] as those are the coefficients of (a+b)
    elif num == 1:
        return([1, 1])
# otherwise we create a for loop that will loop through num-1 iterations - I of every loop here as the making of one row
# in that loop we create a for loop over the save_variable and save_variable[1:] which will let us loop through every possible pair.
# the reason I do this is because each co-efficient in the new row is equal to the addition of the two co_efficients directly above it in the previous row.
# I then add every sum of every pair to the current-variable.
# add 1 to the start and end and then I have the co-efficients of the row.
# equate save_variable to current_variable
# then append save_variable to history_variable
# it repeats itself and finally history_variable is a list of lists each list containing the co-efficients of every row.
    for i in range(num-1):
        for item in zip(save_variable, save_variable[1:]):
            amount += sum(item)
            current_variable.append(amount)
            amount = 0
        current_variable.append(1)
        current_variable.insert(0, 1)
        save_variable = current_variable
        current_variable = []
        history_variable.append(save_variable)
    return history_variable
# this is essentially adding the a's and b's to the co-efficients
# specify the order you want and if the order == 0 or 1 then it just prints out 1 or (1a + 1b)
# otherwise we make variable co-efficients and call basic_pascals to it.
# power a will equal the highest power possible depending on the order of the row, i.
# power b will equal 0. As you move through every term in a row, the power in a decreases and b increases
# rest is forming f"string" to add it to the co-efficients
def pascals_triangle():
    # the n value of (a+b)^n
    order = int(input("Enter the order(n) you would like for (a+b)^n: "))
    spacing = order*10
    if order == 0:
        print(1)
    if order == 1:
        print(f"a{get_super('1')} + b{get_super('1')}")
    else:
        co_efficients = basic_pascals(order)
        for i, row in enumerate(co_efficients):
            power_a = i
            power_b = 0
            result = f""
            for item in row:
                a = f"a{power_a}"
                b = f"b{power_b}"
                if i == 0:
                    result += f"{item}"
                elif power_a == 0:
                    result += f"{item}{get_super(b)} + "
                elif power_b == 0:
                    result += f"{item}{get_super(a)} + "
                else:
                    result += f"{item}{get_super(a)}{get_super(b)} + "
                power_a -= 1
                power_b += 1
            result = result.strip(" + ")
            print(result.center(spacing))
pascals_triangle()

Output:
**Calling basic_pascals(8): **

[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1]]

**Calling pascals_triangle(8): **

                                       1                                        
                                   1a¹ + 1b¹                                    
                               1a² + 2a¹b¹ + 1b²                                
                           1a³ + 3a²b¹ + 3a¹b² + 1b³                            
                       1a⁴ + 4a³b¹ + 6a²b² + 4a¹b³ + 1b⁴                        
                  1a⁵ + 5a⁴b¹ + 10a³b² + 10a²b³ + 5a¹b⁴ + 1b⁵                   
              1a⁶ + 6a⁵b¹ + 15a⁴b² + 20a³b³ + 15a²b⁴ + 6a¹b⁵ + 1b⁶              
         1a⁷ + 7a⁶b¹ + 21a⁵b² + 35a⁴b³ + 35a³b⁴ + 21a²b⁵ + 7a¹b⁶ + 1b⁷          
     1a⁸ + 8a⁷b¹ + 28a⁶b² + 56a⁵b³ + 70a⁴b⁴ + 56a³b⁵ + 28a²b⁶ + 8a¹b⁷ + 1b⁸   

Improvements:
I want to make my code a bit more concise and easier to understand. I even have to think about why I do certain things sometimes. Any improvements please do share. Thanks.