我对此代码有疑问,应该做的是:
a
b c
a b c
a b c a
b c a b c
我想创建一个函数金字塔(n),其中n是行数。我想用abc'来实现它。我可以创建看起来像这样的三角形,但没有改变的字母。我想到了一些从1到3的循环,但不能提出一些它不会这样做的东西:
a
b b
c c c
a a a a
b b b b b
或者打印多次(就像循环中的循环(对于行)一样(从1到3,用于更改字母))。
这些是我的尝试:
def pyramid(n):
word = 'abc'
for i in range(1, n+1):
print (" "*(n-i), " ".join(word[1]*i))
""" Just for help, to see how it works, if I can't come up with something
while looking at it. (n-1) would be (n-i) in loop.
print(" "*(n-1),'a')
print(" "*(n-2),'b','c')
print(" "*(n-3),'a','b','c')
print(" "*(n-4),'a','b','c','a')
print(" "*(n-5),'b','c','a','b','c')
"""
""" Corectly looking solution, but just for one number.
def pyramid(n):
for i in range(1, n+1):
print (" "*(n-i), " ".join(str(n)*i))
"""
答案 0 :(得分:1)
以下是使用itertools.cycle
,itertools.islice
和functools.partial
执行此操作的一种方法:
from itertools import cycle, islice
from functools import partial
def pyramid(n):
c = cycle("abc") #cycle returns items in cycle
max_width = (2*n) - 1 #determine the max width(bottom row)
f = partial("{:^{width}}".format, width=max_width)
for i in range(1, n+1):
print (f(" ".join(islice(c, i))))
如果您不想导入任何内容,那么您必须保留一个全局计数器,每次打印一个字符时都会递增,因此您必须使用counter % 3
来访问下一个字符来自"abc"
:
def pyramid(n):
word = "abc"
counter = 0
for i in range(1, n+1):
print (" "*(n-i), end="")
for j in range(i):
print (word[counter%len(word)], end=" ")
counter += 1
print()