【问题标题】:Recursive Pascals Triangle Layout递归帕斯卡三角布局
【发布时间】:2016-08-23 00:48:43
【问题描述】:

所以我已经设法让 Pascals Triangle 成功打印出打印的数字,但是,我无法使用以下方法获得正确的格式:

n = int(input("Enter value of n: "))


def printPascal(n):
    if n <= 0:      #must be positive int
        return "N must be greater than 0"
    elif n == 1:    #first row is 1, so if only 1 line is wanted, output always 1
        return [[1]]
    else:
        next_row = [1] #each line begins with 1              
        outcome = printPascal(n-1)
        prev_row = outcome[-1]
        for i in range(len(prev_row)-1):    #-1 from length as using index
            next_row.append(prev_row[i] + prev_row[i+1])
        next_row += [1]  
        outcome.append(next_row)     #add result of next row to outcome to print
    return outcome


print(printPascal(n))

这打印为:

Enter value of n: 6
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]

这是正确的,但是我希望它被格式化为直角三角形,例如:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

我的问题是,我是这种语言的新手,无法确定在我的代码中将拆分等放在哪里,以便能够让它像这样打印。 任何朝着正确方向的帮助或推动将不胜感激。 谢谢。

【问题讨论】:

    标签: python python-3.x recursion pascals-triangle


    【解决方案1】:

    您想使用str.join() 函数,该函数打印出由字符串分隔的列表中的所有元素:

    >>> L = printPascal(6)
    >>> for row in L:
    ...     print ' '.join(map(str, row))
    ... 
    1
    1 1
    1 2 1
    1 3 3 1
    1 4 6 4 1
    1 5 10 10 5 1
    

    ' '.join(list) 表示您正在打印列表中的每个元素,并用空格分隔 (' ')。

    但是,列表中的每个元素都必须是字符串,join 函数才能工作。你的是整数。为了解决这个问题,我通过map(str, row) 将所有整数更改为字符串。这相当于:

    new_list = []
    for item in row:
        new_list.append(str(item))
    

    或者作为列表理解:

    [str(item) for item in row]
    

    【讨论】:

    • 我明白你的意思,它已经让它在单独的行上打印,但是它现在打印每一步,使得输出为 1 1 1 1 1 1 1 2 2 1 1 1 1 1 2 1 1 3 3 1 等等。我想我可能在代码中输入了错误的位置?
    • 等待。我现在明白了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多