Home > Software engineering >  how can i generate circles in the Pascal's triangle?
how can i generate circles in the Pascal's triangle?

Time:03-30

Our assignment task is on recursion to develop the Pascal Triangle and circle the generated numbers in a red font. I managed to generate the Pascal triangle after user input, however how do K proceed to make the numbers have a red font and be circled?

I used recursion to achieve the pascal triangle after user enters no. of rows, but now am stuck on how to make the numbers encircled. Below is the code I used.


    rows = int(input("enter number of rows:")) 
    list1 = [] #empty list 
    for i in range(rows): 
         list2 = [] #sublist to print numbers
         for col in range(i 1):        
              if col == 0 or col == i:
                 list2.append(1)     
             else:
                  list2.append(list1[i - 1][col - 1]   list1[i - 1][col])
    list1.append(list2)   
        for col in range(rows-1-i):
            print(format("","<2"), end='')   
        for col in range(i 1):
            print(format(list1[i][col],"<3"), end='') 
    print()
    ```

CodePudding user response:


In order to make the console text red you can use:

print("\033[31m" string)

The details on how it works you can find here: https://stackabuse.com/how-to-print-colored-text-in-python/

I don't really understand what is the expecting "circle" output but you can play with this script:

list_of_all_elements = []
for item in list1:
    list_of_all_elements.extend(item)

half_length = len(list_of_all_elements) // 2   1
symbol = "  "
for i in range(half_length):
    # Number of symbols in the start of the row.
    temp = symbol * (half_length//2 - i if i <= half_length//2 else i - half_length//2)

    # First row.
    if i == 0:
        temp  = str(list_of_all_elements[i])
    # Both "elifs" - last row.
    elif i == half_length - 1 and len(list_of_all_elements) % 2 == 0:
        temp  = " "   str(list_of_all_elements[half_length-1])
    elif i == half_length - 1 and len(list_of_all_elements) % 2 != 0:
        temp  = str(list_of_all_elements[half_length-1])   " "   str(list_of_all_elements[half_length])
    # Middle rows.
    else:
        number_of_middle_symbols = symbol*(2*i-1 if i <= half_length//2 else 4*half_length//2 - 2*i - 1)
        temp  = str(list_of_all_elements[i])   number_of_middle_symbols   str(list_of_all_elements[-i])

    # Printing the current row in red.
    print("\033[31m"   temp)

Here list1 is the list generated by your code. I would say it provides the output which looks more like a rombus than a circle, but this script could be a place to start with.

  • Related