我创造了一个Pascal的三角形。一切都按我想要的方式运作。我现在想要改变三角形中特定数字的颜色。我希望对角线有不同的颜色,即:计数数字为蓝色,三角形数字为橙色。有没有办法可以改变不同行中数字的颜色,甚至设置一系列颜色(一行中的每个数字都是蓝色,红色,橙色,黄色.....然后以下类似会重新启动顺序,但红色)?
# Pascal's Triangle
def multiplicative(n, k):
result = 1
for i in range(1, k+1):
result = result * (n-(k-i))/i
return result
def pascal_level(n):
lists = []
ns = range(n)
for n in ns:
nlist = []
for k in range(n+1):
nlist.append(multiplicative(n, k))
nlist = ' '.join(map(str, nlist))
lists.append(nlist)
return lists
def center(strings):
maxlistlen = len(max(strings, key=len))
for i, s in enumerate(strings):
diff = maxlistlen - len(s)
pad = ' '*(diff/2)
yield str(i)+'-> '+pad+s
answer = int(raw_input("How many levels do you want? \n"))
ps = pascal_level(answer)
for r in center(ps):
print r
编辑 - 我对此有一个有限的理解,所以我将不得不玩这些建议。感谢您的帮助,我会在完成后发布更新。我添加了一张类似于我想要创建的图片。Example
答案 0 :(得分:1)
您可以使用像colored这样的库来更改前景色和背景色,即使在同一行也是如此。
类似的东西:
from colored import stylize, fg
offset = 42 # Starting color
# ...
def pascal_level(n):
lists = []
ns = range(n)
for n in ns:
nlist = []
colors = []
for k in range(n+1):
nlist.append(multiplicative(n, k))
color = fg(k + offset) if k + 1 < n//2 else fg(n - k + offset)
colors.append(color)
nlist = ' '.join(stylize(str(x), color) for x, color in zip(nlist, colors))
lists.append(nlist)
return lists
答案 1 :(得分:1)