[Introduction to Algorithms and Data Structures] [Day4] Implement the generalized Fibonacci sequence with the minimum number of lines

Write a function Tribonacci (signature, n), if we want to start with [1,1,1] as input, we can get the generalized Fibonacci sequence: [1, 1, 1, 3, 5, 9, 17, 31,…] The
input parameter signature is a list containing the first three digits, n represents the length of the returned sequence (non-negative), you need to return the complete generalized Fibonacci sequence
Insert picture description here
method 1:

def tribonacci(signature, n):   
    [signature.append(sum(signature[-3:]))  for i in range(3, n)]
    return signature[:n]
print(tribonacci([1,1,1],10))
print(tribonacci([300,200,100],0))
print(tribonacci([0.5,0.5,0.5],30))

Insert picture description here
Method 2:

def tribonacci(s, n):
    for i in range(3, n): 
        s.append(s[i-1] + s[i-2] + s[i-3])
    return s[:n]
print(tribonacci([1,1,1],10))
print(tribonacci([300,200,100],0))
print(tribonacci([0.5,0.5,0.5],30))

Insert picture description here

Published 42 original articles · praised 28 · visits 4961

Guess you like

Origin blog.csdn.net/KaelCui/article/details/105351120