PythonはYang Huiの三角アルゴリズムを実装しています

Pythonでは、Yanghui三角形は常にアルゴリズムテストとして取り出されるので、Yanghui三角形とは何ですか?定義を表示

まず、次のヤンフイトライアングルの凡例を見てみましょう。

観察すると、Yanghui三角形の各行の最初と最後の数値は1であり、3番目の行の1以外の数値は、その左上と右上の数値の合計です。

その後、法律を知ってからコードを書き始めることができます

def triangles(row):    
    count = 0
    while count < row:
        arr = []
        for i in range(count+1):
            if i > 0 and i < count:
                arr.append(lastList[i-1] + lastList[i])
            else:
                arr.append(1)
        lastList = arr
        yield arr
        count += 1


for t in triangles(10):
    print(t)

上記のコードを記述した後、多くのコードを見て、コードを簡略化できますか?

次に、次のコードがあります

def triangles(row):
    count = 0
    while count < row:
        arr = [arr[i-1] + arr[i] if i > 0 and i < count else 1 for i in range(count+1)]
        yield arr
        count += 1


for t in triangles(10):
    print(t)

このコードははるかに簡潔です

おすすめ

転載: blog.csdn.net/qczxl520/article/details/108734692