Consider having a cow that gives a child every year from her fourth year of life on and all her subsequent children do the same.

After n years how many cows will you have?
Return null if n is not an integer.

Note: Assume all the cows are alive after n years.

Source: codewars | Difficulty: EASY
Tags: Mathematics

Ad-hoc

Starter code: def count_cows(n):
	

Solutions:
def count_cows(n):
	if not isinstance(n, int):
		return None
	return 1 if n < 3 else count_cows(n - 1) + count_cows(n - 3)


def count_cows(n):
	if isinstance(n, int):
		(a, b, c) = (1, 0, 0)
		for _ in range(n):
			(a, b, c) = (c, a, b + c)
		return a + b + c


def count_cows(n):
	if type(n) != int:
		return None
	(a, b, c, d) = (1, 0, 0, 0)
	for _ in range(n):
		(a, b, c, d) = (c + d, a, b, c + d)
	return a + b + c + d


solution = __import__('functools').lru_cache(maxsize=None)(lambda n: 1 if n < 3 else solution(n - 1) + solution(n - 3))

def count_cows(n):
	if type(n) == int:
		return solution(n)


def count_cows(n):
	if isinstance(n, int):
		return 1 if n < 3 else count_cows(n - 1) + count_cows(n - 3)


from functools import lru_cache

@lru_cache(maxsize=None)
def f(n):
	if n < 3:
		return 1
	return f(n - 3) + f(n - 1)

def count_cows(n):
	if not isinstance(n, int):
		return None
	return f(n)


def count_cows(n):
	if not isinstance(n, int):
		return None
	cows = [0, 0, 0, 1]
	for _ in range(n):
		cows = [cows[0] + cows[1], cows[2], cows[3], cows[0] + cows[1]]
	return sum(cows)


from collections import deque

def count_cows(n):
	if not isinstance(n, int):
		return None
	calves = deque([1, 0, 0])
	cows = 0
	for i in range(n):
		cows += calves.pop()
		calves.appendleft(cows)
	return cows + sum(calves)


def count_cows(n):
	if not isinstance(n, int):
		return None
	cows = [1]
	old_cows = 0
	for _ in range(n):
		cows = [old_cows] + cows
		if len(cows) >= 3:
			old_cows += cows.pop()
	return sum(cows) + old_cows