[英]Reversing the output of a while sequence in python 3?
作業是寫一個程序,打印出函數2^n的圖,如下:
*
**
****
********
****************
********************************
****************
********
****
**
*
我能夠對后半部分進行編程(在示例中從 2^6 向下),但我不知道如何反轉while
函數來創建前半部分。 到目前為止,這是我的代碼:
import math
n=None
while n is None:
try:
n=input("Enter an integer for the power of two you wish to represent: ")
n=int(n)
except ValueError:
print("That is not an integer. Please try again.")
else:
while n>=0:
amt=(math.pow(2,n))
print('*'*int(amt))
n=int(n)-1
其中,當我輸入 6 時,輸出
********************************
****************
********
****
**
*
那么我如何讓它做上半場呢?
import math
def draw(n):
i = 0;
while i <= n:
d = i
if i > n /2:
d = n - i;
print("*" * int(math.pow(2,d)))
i+=1
draw(12)
對於 n = 12;
*
**
****
********
****************
********************************
****************************************************************
********************************
****************
********
****
**
*
您可以計算結果值並將它們存儲在一個列表中,然后將列表的兩半反轉以獲得預期的結果
import math
n=None
while n is None:
try:
n=input("Enter an integer for the power of two you wish to represent: ")
n=int(n)
except ValueError:
print("That is not an integer. Please try again.")
else:
lst = [math.pow(2,abs(r)) for r in range(0-n, n)]
lst = lst[len(lst)/2:] + lst[:len(lst)/2+1]
for item in lst:
print('*'*int(item))
我不會使用 while 函數。 從我的角度來看,for 循環在這里更好。 因此,您可以例如在兩個 for 循環中使用您的代碼,一個是升序,另一個是降序。
for power in range(n):
amt=(math.pow(2,power))
print('*'*int(amt))
for power in range(n-1)[::-1]:
amt=(math.pow(2,power))
print('*'*int(amt))
您可以通過以下方式在一個循環中解決此問題:
i=n*-1
while i<=n:
x =n-abs(i)
amt=(math.pow(2,x))
print('*'*int(amt))
i=i+1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.