社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python中的Pascal三角(11的幂)

Ned • 5 年前 • 1576 次点击  

我想编写一个Python程序,打印出输入行数的Pascal三角形。 我的代码如下:

inc = int(input('Input number of rows: '))
n = 0
row = []
while n <= inc:
    m = 11 ** n
    row.append(m)
    n += 1
for i in range(0, len(row)):
    row[i] = str(row[i])

result = '\n'.join(row)
print(result)

我的输出是:

1
11
121

我想把每一行中的每个符号分开,这样看起来就像帕斯卡三角形。我该如何实现?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52007
 
1576 次点击  
文章 [ 3 ]  |  最新文章 5 年前
lenik
Reply   •   1 楼
lenik    5 年前

这要简单得多:

ROWS = 5

def row( a, b ) :
   return ' ' * (b-a-1) + ' '.join([i for i in str(11**a)])

for i in range(ROWS) :
    print row( i, ROWS )

输出:

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

如果你想让它在python3中工作,在 print( .. ) 打电话来。

Kent Shikama
Reply   •   2 楼
Kent Shikama    5 年前

每行可以缩进 len(row) - i 然后对每个字符进行空格,使每行的长度是原来的两倍,以平衡其他正确的对齐方式。

inc = int(input('Input number of rows: '))
n = 0
row = []
while n <= inc:
    m = 11 ** n
    row.append(m)
    n += 1
for i in range(0, len(row)):
    indent = " " * (len(row) - i)
    spaced_row = " ".join(list(str(row[i])))
    row[i] = indent + spaced_row

result = '\n'.join(row)
print(result)

输出

Input number of rows: 3
    1
   1 1
  1 2 1
 1 3 3 1
Sayandip Dutta
Reply   •   3 楼
Sayandip Dutta    5 年前

你很接近,你可以 str.center 每行:

inc = int(input('Input number of rows: '))
n = 0
row = []
while n < inc:
    m = 11 ** n
    row.append(m)
    n += 1
for i in range(0, len(row)):
    row[i] = ' '.join(list(str(row[i])))
for i in range(0, len(row)):
    row[i] = row[i].center(len(row[-1]),' ')
result = '\n'.join(row)
print(result)

输出:

Input number of rows: 4
   1   
  1 1  
 1 2 1 
1 3 3 1

较短的版本是:

inc = int(input('Input number of rows: '))
max_len = 2 * len(str(11**inc)) - 1
row = (' '.join([*str(11**p)]).center(max_len,' ') for p in range(inc))
print(*row, sep='\n')

输出:

输入行数:4
1个
11个
1 2 1号
1 3 3 1