Skip to main content
Spelling, grammar, formatting
Source Link
Toby Speight
  • 81.7k
  • 14
  • 101
  • 308

PascalsPascal's 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: In my code the user is asked an input for what order (n) they want and it outputs Pascal's triangle.

The Code

I added in comments to help youryou understand my reasoning.

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

Output

Calling basic_pascals(8)

**Calling pascals_triangle(8): **

Calling pascals_triangle(8)

Improvements

Improvements:
I 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.

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.

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

**Calling pascals_triangle(8): **

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.

Pascal's triangle is a simple and effective way to expand a set of brackets in the form (a + b).

In my code the user is asked an input for what order (n) they want and it outputs Pascal's triangle.

The Code

I added in comments to help you understand my reasoning.

Output

Calling basic_pascals(8)

Calling pascals_triangle(8)

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.

Tweeted twitter.com/StackCodeReview/status/1564719623295082497
Became Hot Network Question
Title, tags, removed unnecessary intro verbage
Source Link
AJNeufeld
  • 34k
  • 5
  • 39
  • 101

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 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

I added in comments to help your understand my reasoning.

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.

Pascal's Triangle Generator

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.

added 6 characters in body
Source Link
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()
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()
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()
deleted 2 characters in body
Source Link
Loading
edited title
Link
Loading
Source Link
Loading