私は Google の App Inventor のバックグラウンドを持っています。オンラインクラスを受講しています。
タスク: ネストされた while ループでアスタリスクから三角形を作成します。三角形の底辺は 19 個のアスタリスク、高さは 10 個のアスタリスクです。
ここにいます。
Num = 1
while Num <= 19:
print '*'
Num = Num * '*' + 2
print Num
私は Google の App Inventor のバックグラウンドを持っています。オンラインクラスを受講しています。
タスク: ネストされた while ループでアスタリスクから三角形を作成します。三角形の底辺は 19 個のアスタリスク、高さは 10 個のアスタリスクです。
ここにいます。
Num = 1
while Num <= 19:
print '*'
Num = Num * '*' + 2
print Num
Num = Num * '*' + 2 で行っていることは次のとおりです。
n = 0
w = 19
h = 10
rows = []
while n < h:
rows.append(' '*n+'*'*(w-2*n)+' '*n)
n += 1
print('\n'.join(reversed(rows)))
プロデュース
*
***
*****
*******
*********
***********
************* #etc...
*************** #2 space on both sides withd-4 *
***************** #1 space on both sides, width-2 *
******************* #0 spaces
>>> len(rows[-1])
19
>>> len(rows)
10
ここにクールなトリックがあります。Python では、文字列に を使用して数値を掛けることができます*
。これは、連結された文字列の多くのコピーになります。
>>> "X "*10
'X X X X X X X X X X '
また、次のように 2 つの文字列を連結できます+
。
>>> " "*3 + "X "*10
' X X X X X X X X X X '
したがって、Python コードは単純な for ループにすることができます。
for i in range(10):
s = ""
# concatenate to s how many spaces to align the left side of the pyramid?
# concatenate to s how many asterisks separated by spaces?
print s
string-objects から「center」メソッドを使用できます。
width = 19
for num in range(1, width + 1, 2):
print(('*' * num).center(width))
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
通常、ネストされた while ループをこの問題に使用することはありませんが、1 つの方法を次に示します。
rows = 10
while rows:
rows -=1
cols = 20
line = ""
while cols:
cols -=1
if rows < cols < 20-rows:
line += '*'
else:
line += ' '
print line
(count - 1) * 2 + 1
各行のアスタリスクの数を計算します。
count = 1
while count <= 10:
print('*' * ((count - 1) * 2 + 1))
count += 1
もちろん、簡単な方法で行くことができます。
count = 1
while count <= 20:
print('*' * count)
count += 2