Simulating Fibonacci's Rabbits with multiple offsprings using python

1k Views Asked by At

Suppose I start with one pair of rabbit and each pair reproduces 3 pairs of rabbits. Let new rabbit pair be N and mature rabbit pair be M:

 N    0 
 M    1
MNNN  4
MNNN MMM MMM MMM 19 

So the series is 0 1 4 19

How do we do this on Python using loops:

I tried:

x="N" #new rabbit pair
x=x.replace("N","M")
x
'M' #Mature rabbit pair
x=x.replace("M","MNNN")
x
'MNNN'
x=x.replace("M","MN")
x=x.replace("N","M")
x
'MNNNMMM'

How do I put this in a loop using xrange/range function.

Thanks

2

There are 2 best solutions below

1
On BEST ANSWER

The process for a single step is to replace all 'M's with 'MNNN' and all 'N's with 'M', so:

def step(state):
    return ''.join(['MNNN' if s == 'M' else 'M' for s in state])

For example:

>>> s = 'N'
>>> for _ in range(5):
    print s, len(s)
    s = step(s)


N 1
M 1
MNNN 4
MNNNMMM 7
MNNNMMMMNNNMNNNMNNN 19
4
On

You can try something like this -

mature = 'M'
kid = 'N'
start = 'N'
for i in range(10):
    ms = start.count(mature)
    start = start.replace(kid ,mature)
    start = start + kid * (ms * 3)
    print(start)

For performance and memory usage - you can use -

mature = 'M'
kid = 'N'
start = (0,1)
print(mature * start[0] + kid * start[1])
for i in range(10):
    newmature = start[1] 
    newkid = start[0] * 3
    start = (start[0] + newmature , start[1] + newkid - newmature)
    print(mature * start[0] + kid * start[1] + " - " + str(start[0] + start[1]))