利用python画钻石_Python空心钻石

你的问题是你继续使用打印. print语句(以及Python 3中的函数)将在您打印的内容后添加换行符,除非您明确告诉它不要.你可以在Python 2中这样做:

print '*', # note the trailing comma

或者在Python 3中(使用print函数),如下所示:

print('*', end='')

我的解决方案

我对问题采取了自己的看法并提出了这个解决方案:

# The diamond size

l = 9

# Initialize first row; this will create a list with a

# single element, the first row containing a single star

rows = ['*']

# Add half of the rows; we loop over the odd numbers from

# 1 to l, and then append a star followed by `i` spaces and

# again a star. Note that range will not include `l` itself.

for i in range(1, l, 2):

rows.append('*' + ' ' * i + '*')

# Mirror the rows and append; we get all but the last row

# (the middle row) from the list, and inverse it (using

# `[::-1]`) and add that to the original list. Now we have

# all the rows we need. Print it to see what's inside.

rows += rows[:-1][::-1]

# center-align each row, and join them

# We first define a function that does nothing else than

# centering whatever it gets to `l` characters. This will

# add the spaces we need around the stars

align = lambda x: ('{:^%s}' % l).format(x)

# And then we apply that function to all rows using `map`

# and then join the rows by a line break.

diamond = '\n'.join(map(align, rows))

# and print

print(diamond)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值