Thursday, February 3, 2022

Tribonacci Codewars Python

Description:

Well met with Fibonacci bigger brother, AKA Tribonacci.

As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :(

So, if we are to start our Tribonacci sequence with [1, 1, 1] as a starting input (AKA signature), we have this sequence:

[1, 1 ,1, 3, 5, 9, 17, 31, ...]

def tribonacci(signature, n):
    if n <= 2:
        return signature[:n]
    res = 0
    for i in range(n - len(signature)):
        res = sum(signature[-3:])
        signature.append(res)
    return signature

def tribonacci(signature, n):
  res = signature[:n]
  for i in range(n - 3): res.append(sum(res[-3:]))
  return res
# For range in n - len(signature) sum the last three and append to the signature



Related Posts


No comments :

Post a Comment