0

I am working with series like Fibonacci series... (In Fibonacci series the nth term is the sum of n-1 and n-2 only.) But in my case I want to nth term is the sum of half of the previous terms.. for example:

n=5
Output should be: [0, 1, 1, 2, 3]

n=12
Output should be: [0, 1, 1, 2, 3, 6, 11, 22, 42, 84, 165, 330]
def my_function(n):
    
    list1=[0,1]
    for i in range(0,n-2):
        if(i>2):
            value=sum(list1[i//2+1:])
        else:
            value=list1[i]+list1[i+1]
        list1.append(value)
    return list1
    
print(my_function(5))

I have done this without recursive function but I am thinking how to do it using recursively and memoization. Can you help me to solve this..

khelwood
  • 52,115
  • 13
  • 74
  • 94
  • Does this answer your question? [How to write the Fibonacci Sequence?](https://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence) – kerolloz Feb 27 '22 at 07:27
  • I don't need a Fibonacci series I want nth term is the sum of half of the previous terms. – Muhammad Usama Feb 27 '22 at 07:39

1 Answers1

2

Are you looking for something like this?

# Python has a built-in decorator for memoizing any function automagically.

from functools import lru_cache

@lru_cache(maxsize=None)
def my_func_rec(n):
    if n == 1:
        return [0]
    elif n == 2:
        return [0,1]
    else:
        prev = my_func_rec(n-1)
        prev.append(sum(prev[(n-1)//2:]))
        return prev

print(my_func_rec(12)) # [0, 1, 1, 2, 3, 6, 11, 22, 42, 84, 165, 330]
kerolloz
  • 338
  • 1
  • 15