由'abc'组成的三角形 [python]

-1 投票
1 回答
1299 浏览
提问于 2025-04-28 10:24

我在这段代码上遇到了问题,它应该完成的功能是:

    a
   b c
  a b c
 a b c a
b c a b c

我想创建一个名为 pyramid(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))
"""
暂无标签

1 个回答

1

这里有一种方法可以实现这个功能,使用了 itertools.cycleitertools.islicefunctools.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()

撰写回答