-
Notifications
You must be signed in to change notification settings - Fork 0
/
rabbits_multiplying.py
52 lines (47 loc) · 1.69 KB
/
rabbits_multiplying.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Rabbits Multiplying. Exercise from a Udacity course.
# A (slightly) more realistic model of rabbit multiplication than the Fibonacci
# model, would assume that rabbits eventually die. For this question, some
# rabbits die from month 6 onwards.
#
# Thus, we can model the number of rabbits as:
#
# rabbits(1) = 1 # There is one pair of immature rabbits in Month 1
# rabbits(2) = 1 # There is one pair of mature rabbits in Month 2
#
# For months 3-5:
# Same as Fibonacci model, no rabbits dying yet
# rabbits(n) = rabbits(n - 1) + rabbits(n - 2)
#
#
# For months > 5:
# All the rabbits that are over 5 months old die along with a few others
# so that the number that die is equal to the number alive 5 months ago.
# Before dying, the bunnies reproduce.
# rabbits(n) = rabbits(n - 1) + rabbits(n - 2) - rabbits(n - 5)
#
# This produces the rabbit sequence: 1, 1, 2, 3, 5, 7, 11, 16, 24, 35, 52, ...
#
# Define a procedure rabbits that takes as input a number n, and returns a
# number that is the value of the nth number in the rabbit sequence.
# For example, rabbits(10) -> 35. (It is okay if your procedure takes too
# long to run on inputs above 30.)
# s = ""
# for i in range(1,12):
# s = s + str(rabbits(i)) + " "
# print s
#
# >>> 1 1 2 3 5 7 11 16 24 35 52
from UnitaryTest.test_tools import TestTools
def rabbits(n):
if n == 1 or n == 2:
return 1
if n >= 3 and n <= 5:
return rabbits(n - 1) + rabbits(n - 2)
if n > 5:
return rabbits(n - 1) + rabbits(n - 2) - rabbits(n - 5)
def main():
t = TestTools()
t.new_test(func=rabbits)
t.evaluate_result(rabbits(10), expected=35)
if __name__ == '__main__':
main()