我的目标是使用python创建一个中空的菱形。
示例输入:
Input an odd Integer:
9示例输出:
*
* *
* *
* *
* *
* *
* *
* *
*但到目前为止,我有以下代码不能正常工作。请帮助我修改代码以实现上述目标:
a=int(input("Input an odd integer: "))
k=1
c=1
r=a
while k<=r:
while c<=r:
print "*"
c+=1
r-=1
c=1
while c<=2*k-1:
print "*"
c+=1
print "\n"
k+=1
r=1
k=1
c=1
while k<=a-1:
while c<=r:
print " "
c+=1
r+=1
c=1
while c<= 2*(a-k)-1:
print ("*")
c+=1
print "\n"
k+=1上面的代码返回的结果与我的目标相去甚远。
Input an odd integer: 7
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*实际上,我正在转换这篇文章中的代码:用C语言编写的http://www.programmingsimplified.com/c/source-code/c-program-print-diamond-pattern,稍后将针对空心的代码进行修改,但我无法获得它……我的转换有问题..
发布于 2013-01-02 21:24:08
你的问题是你一直在使用print。print语句(和Python3中的函数)将在您打印的内容之后添加一个换行符,除非您明确地告诉它不要这样做。你可以在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)发布于 2013-01-02 21:47:02
中空的菱形是方程的解
|x|+|y| = N在整数网格上。因此,将空心菱形作为1行代码:
In [22]: N = 9//2; print('\n'.join([''.join([('*' if abs(x)+abs(y) == N else ' ') for x in range(-N, N+1)]) for y in range(-N, N+1)]))
*
* *
* *
* *
* *
* *
* *
* *
* 发布于 2013-01-02 21:31:24
def diamond(n, c='*'):
for i in range(n):
spc = i * 2 - 1
if spc >= n - 1:
spc = n - spc % n - 4
if spc < 1:
print(c.center(n))
else:
print((c + spc * ' ' + c).center(n))
if __name__ == '__main__':
diamond(int(input("Input an odd integer: ")))https://stackoverflow.com/questions/14122653
复制相似问题