此功能可打印由" *"组成的金字塔。和"&"字符。我希望程序打印出"&"的总数。金字塔中的字符,所以我用.count计算了多少次"&"出现在每一行。问题是我无法将变量z的输出加在一起得到总时间"&"出现在金字塔中。有什么想法吗?
import random
from random import choice
from random import randint
def pyramid():
min_pyramid_size = 5
max_pyramid_size = 10
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*&')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
z = x.count('&')
print(z)
pyramid()
更新: 我尝试将z移出循环,它只打印了"&"在最后一行。
import random
from random import choice
from random import randint
def pyramid():
min_pyramid_size = 3
max_pyramid_size = 5
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*&')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
z = 0
z += x.count('&')
print(z)
pyramid()
答案 0 :(得分:2)
Haven没有运行它,但你需要一个在for循环之外的变量来保存''
的总数。def pyramid():
min_pyramid_size = 5
max_pyramid_size = 10
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
total_z = 0
for i in range(num_rows):
x = ''.join(str(random.choice('*&')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
z = x.count('&')
total_z = total_z + z
print(z)
pyramid()
答案 1 :(得分:0)
在for循环范围之外定义z
z = 0
并使用
z += x.count('&')
而不是
z = x.count('&')
答案 2 :(得分:0)
试试这个: -
import random
from random import choice
from random import randint
def pyramid():
min_pyramid_size = 5
max_pyramid_size = 10
z = 0
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*&')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
z = z + x.count('&')
print(z)
pyramid()
答案 3 :(得分:0)
这是使用列表理解的更紧凑的解决方案:
def pyramid(min_size=5, max_size=10):
N = randint(min_size, max_size)
x = ''.join(' ' * (N-i) + ''.join(choice('*&') for j in range(2*i+1)) + '\n' for i in range(N))
print(x)
print(x.count('&'))
演示:
>>> pyramid()
&
&*&
&**&*
&&&**&*
&***&&&&&
&&&&*&&****
&&&&*&***&&**
*&&&&**&&&&&**&
&*&***&*&&&*&&*&*
47
您可以通过将适当的参数传递给函数来更改金字塔的最小和最大大小的值,例如pyramid(min_size=8, max_size=12)
。
答案 4 :(得分:0)
您需要有两个变量,一个用于内部,一个用于外部计数。
$ f=filename_2016-01-01
$ echo ${f#*_}
2016-01-01
$ f=2016-01-01_filename
$ echo ${f%_*}
2016-01-01
$ f=20160101-filename
$ echo ${f%-*}
20160101
$ f=1451606400-filename
$ echo ${f%-*}
1451606400