使用递归的侧身三角形图案

时间:2019-03-21 21:37:47

标签: python recursion

我正在尝试使用Python中的递归来实现横向三角形模式。每次运行代码时,都会出现无限循环或打印长行。这是我要打印的代码:

triangle(4,7)

- - - -
- - - - - 
- - - - - -
- - - - - - -
- - - - - -
- - - - -
- - - -

这是我的代码:

def triangle(a,b):
    if a > b:
        return
    for i in range(0,a):
        print("-",end="")

    triangle(a+1,b)

    for i in range(0,a):
        print("-",end="")

3 个答案:

答案 0 :(得分:0)

def triangle(a,b):
    if a > b:
        return
    if a==b:
        print(a*"- ")
    else:
        print(a*"- ")
        triangle(a+1,b)
        print(a*"- ")

triangle(4,7)

输出

- - - - 
- - - - - 
- - - - - - 
- - - - - - - 
- - - - - - 
- - - - - 
- - - - 

答案 1 :(得分:0)

def triangle(a, b):
    if a > b:
        return

    if a != b:  # print the longest line only once
        print((a - 1) * "- " + "-")  # print without trailing whitespace

    triangle(a + 1, b)
    print((a - 1) * "- " + "-")  # print without trailing whitespace

答案 2 :(得分:0)

您可以执行更简单的递归:

def print3angle(a,b):
    print("- "*a)
    if a<b :
        print3angle(a+1,b)
        print("- "*a)

如果您想同时支持两个方向,则可以将其更改为:

def print3angle(a,b):
    print("- "*a)
    if a!=b :
        print3angle(a+(a<b)-(a>b),b)
        print("- "*a)

print3angle(4,7)

- - - - 
- - - - - 
- - - - - - 
- - - - - - - 
- - - - - - 
- - - - - 
- - - -

print3angle(7,4)

- - - - - - - 
- - - - - - 
- - - - - 
- - - - 
- - - - - 
- - - - - - 
- - - - - - -