从循环构造算术级数

2024-10-03 21:32:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图编制一个程序来计算帕斯卡三角形的对角线系数。你知道吗

enter image description here

对于那些不熟悉它的人,序列的一般术语写在下面。你知道吗

第一行=1。。。。你知道吗

第二行=N0(自然数)//1=1 2 3 4 5。。。。你知道吗

第三行=N0(N0+1)//2=1 3 6 10 15。。。你知道吗

第四行=N0(N0+1)(N0+2)//6=1 4 10 20 35。。。你知道吗

每一行的后续序列都遵循特定的模式,我的目标是将这些序列输出到一个for循环中,并以单元数作为输入。你知道吗

def figurate_numbers(units):
    row_1 = str(1) * units
    row_1_list = list(row_1)

    for i in range(1, units):
    sequences are 
                  row_2 = n // i 
                  row_3 = (n(n+1)) // (i(i+1))
                  row_4 = (n(n+1)(n+2)) // (i(i+1)(i+2))

>>> def figurate_numbers(4): # coefficients for 4 rows and 4 columns
[1, 1, 1, 1]
[1, 2, 3, 4]
[1, 3, 6, 10]
[1, 4, 10, 20]   # desired output

如何在一个循环中对ni进行迭代,以便相应行的每个序列都输出系数?你知道吗


Tags: 程序fordef序列listrow术语units
2条回答

可以使用映射或列表来隐藏循环。你知道吗

def f(x, i): 
    return lambda x: ...

row = [ [1] * k ]

for i in range(k):
   row[i + 1] = map( f(i), row[i])

其中f是一个函数,该函数依赖于行的前一个元素。你知道吗

另一种可能是使递归Fibbonachi适应行。Numpy库允许数组arifmetics,所以甚至不需要map。python也有预定义的库,用于组合的数量等,也许可以使用。你知道吗

为了有效地计算,无需嵌套循环,请使用基于有理数的解决方案

https://medium.com/@duhroach/fast-fun-with-pascals-triangle-6030e15dced0。你知道吗

from fractions import Fraction

def pascalIndexInRowFast(row,index):
    lastVal=1
    halfRow = (row>>1)

    #early out, is index < half? if so, compute to that instead
    if index > halfRow:     
        index = halfRow - (halfRow - index)

    for i in range(0, index):
        lastVal = lastVal * (row - i) / (i + 1)

return lastVal

def pascDiagFast(row,length):

    #compute the fractions of this diag
    fracs=[1]*(length)
    for i in range(length-1):
        num = i+1
        denom = row+1+i
        fracs[i] = Fraction(num,denom)

    #now let's compute the values
    vals=[0]*length

    #first figure out the leftmost tail of this diag
    lowRow = row + (length-1)
    lowRowCol = row
    tail = pascalIndexInRowFast(lowRow,lowRowCol)

    vals[-1] = tail

    #walk backwards!
    for i in reversed(range(length-1)):
        vals[i] = int(fracs[i]*vals[i+1])

return vals

不要重新设计三角形:

>>> from scipy.linalg import pascal
>>> pascal(4)
array([[ 1,  1,  1,  1],
       [ 1,  2,  3,  4],
       [ 1,  3,  6, 10],
       [ 1,  4, 10, 20]], dtype=uint64)
>>> pascal(4).tolist()
[[1, 1, 1, 1], [1, 2, 3, 4], [1, 3, 6, 10], [1, 4, 10, 20]]

相关问题 更多 >