2016-11-04 139 views
0

环路我只能创建一个充满钻石,我无法弄清楚如何得到一个空心菱形它unfilled.`#了如何使用,而在蟒蛇

# 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
# 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 

只需打印少两个空间比你打印*的插图中包含两个*的,除非在顶部或底部。

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) * " " + '*') 

    * 
    * * 
* * 
*  * 
* * 
    * * 
    * 
+0

哎呀,你打我:) – nephi12

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 

看看空心和实心符号功能之间的区别,如果您使用的是> =那么你得到了坚实的事情,如果你使用==进行精确comperison那么它仅仅是parimiter

+0

try def circle(row,column,size): \t if(size // 2-row)** 2+(size // 2-column)** 2 <=(size // 2 )** 2: \t \t return'*' \t return'' –