2016-11-04 126 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'' –