如何在帕斯卡三角形中生成圆?



我们的任务是递归开发Pascal三角形,并用红色字体圈出生成的数字。我设法在用户输入后生成了Pascal三角形,但是K如何使数字具有红色字体并被圈出?

在用户输入行数后,我使用递归来实现帕斯卡三角形,但现在我只知道如何将数字圈起来。下面是我使用的代码。


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()
```

为了使控制台文本变为红色,您可以使用:print("33[31m" + string)

有关其工作原理的详细信息,您可以在此处找到:https://stackabuse.com/how-to-print-colored-text-in-python/

我真的不明白期待的是什么;"圆圈";输出,但你可以玩这个脚本:

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("33[31m" + temp)

这里list1是由您的代码生成的列表。我想说,它提供的输出看起来更像一个血栓而不是一个圆圈,但这个脚本可能是一个起点。

最新更新