【问题标题】:Need to print triforce using recursion需要使用递归打印 triforce
【发布时间】:2021-10-10 16:44:14
【问题描述】:

我正在尝试编写一组递归函数来打印Triforce 的 ASCII 艺术版本,但间距无法正确渲染图像。

代码如下:

def space_f(space):
    if space == 0:
        return
    print(" ", end = "")
    space_f(space - 1)
 
def triangle(n):
    if n == 0:
        return
    return '* '*n
    triangle(n - 1)
 
def top_triangle(n, count, base):
    if n == 0:
        return
    space_f(base)
    print(triangle(count - n + 1))
    return top_triangle(n - 1, count, base-1)

def bottom_triangles(n, count, base):
    if n == 0:
        return
    space_f(n-1)
    print(triangle(count - n + 1), triangle(count - n + 1))
    return bottom_triangles(n - 1, count, base-1)


def print_triforce(n):
        if n == 0:
                print(" ")
        height = 2 * n
        base = height - 1
        top_triangle(n, n, base)
        bottom_triangles(n, n, base)

这是调用的预期输出:print_triforce(2):

   * 
  * *
 *   * 
* * * *

然而,实际的输出是:

     * 
    * * 
   * * * 
  *  * 
 * *  * * 
* * *  * * * 

【问题讨论】:

  • 除了“您能告诉我如何修复损坏的代码吗”之外,您对代码的具体问题是什么?

标签: python python-3.x ascii-art


【解决方案1】:

您在 bottom_triangles 函数中没有打印足够的空格,并且还由于在打印多个变量时添加了空格,例如print("a","b") 打印 a b 而不是 ab

将其替换为以下内容,它应该可以工作

def bottom_triangles(n, count, base):
    if n == 0:
        return
    space_f(n-1)
    print(triangle(count - n + 1), end="")
    space_f(n-1)
    space_f(n-1)
    print(triangle(count - n + 1))
    return bottom_triangles(n - 1, count, base-1)

由于上面的 return 语句,三角形函数末尾的 triangle(n - 1) 调用也永远不会被调用。

【讨论】:

    猜你喜欢
    • 2017-03-31
    • 2023-01-20
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多