我只能创建一个填充的钻石,我无法弄清楚如何将它填满。#
# The size of the diamond
N = 7
# The top part (includes the middle row)
i = 0
while i < N // 2 + 1:
print((N // 2 - i) * " " + (2 * i + 1) * "*")
i += 1
# The bottom part
i = 0
while i < N // 2:
print(" " * (i + 1) + "*" * (N - 2 - 2 * i))
i += 1
答案 0 :(得分:1)
您只需在(2*i-1)
个字符之间打印'*'
个空格,而不仅仅是'*'
。并且必须分别处理顶部和底部:
# The size of the diamond
N = 7
# The top part (includes the middle row)
print((N // 2) * " " + '*')
i = 1
while i < N // 2 + 1:
print((N // 2 - i) * " " + '*' + (2 * i - 1) * " " + '*')
i += 1
# The bottom part
i = 0
while i < N // 2 - 1:
print(" " * (i + 1) + '*' + " " * (N - 4 - 2 * i) + '*')
i += 1
print((N // 2) * " " + '*')
*
* *
* *
* *
* *
* *
*
答案 1 :(得分:0)
# The size of the diamond
N = 7
# The top part (includes the middle row)
i = 0
while i < N // 2 + 1:
print((N // 2 - i) * " " + "*" +( ((2 * i -1) * " " + "*") if i > 0 else ""))
i += 1
# The bottom part
i = 0
while i < N // 2:
print(" " * (i + 1) + "*" + ( ( " " * (N - 2 - 2 * i - 2) + "*") if i < (N//2-1) else ""))
i += 1
除了在顶部或底部之外,只打印两个空格,而不是在两个*之间打印*。
答案 2 :(得分:0)
def diamond(size, sym_func):
s = ''
for row in xrange(size):
for column in xrange(size):
if row > size//2: # if bottom half reflect top
row = size - row - 1
if column > size//2: # if right half reflect left
column = size - column - 1
s += sym_func(row,column,size)
s+= '\n'
return s
def solid(row,column,size):
if column >= (size // 2 - row):
return "*"
return " "
def hollow(row,column,size):
if column == (size // 2 - row):
return "*"
return " "
def circle(row,column,size):
if (size//2-row)**2+(size//2-column)**2 <= (size//2)**2:
return '*'
return ' '
print diamond(size=7, sym_func=solid) # The size of the diamond
print diamond(size=7, sym_func=hollow) # The size of the diamond
print diamond(size=17, sym_func=circle) # The size of the diamond
如果你使用&gt; =看看空心符号和实心符号函数之间的区别,那么如果使用==进行精确比较,那么你会得到一个可靠的东西,那么它只是分隔符