Skip to content

Instantly share code, notes, and snippets.

@Swarchal
Created February 19, 2016 13:50
Show Gist options
  • Save Swarchal/7f587a73f4a97c6c3156 to your computer and use it in GitHub Desktop.
Save Swarchal/7f587a73f4a97c6c3156 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Fibonacci Rabbits\n",
"==================\n",
"\n",
"Given 2 positive integers\n",
"\n",
"Return the total number of pairs that will be present after n months if we begin with 1 pair and in each generation produce a litter of k pairs\n",
"\n",
"Begin with 1 pair \n",
"Each pair produces $k$ pairs of offspring \n",
"A pair can only reproduce after they are 1 month old "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Could also do this recursively, but would have to make exceptions for the early values of `n`\n",
"\n",
"If we want to do this in a single loop, will need to watch the order the params are updated, otherwise will be generating number of offspring from a newly updated values without the month gap before they are mature."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python\n",
"-------"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def n_rabbits(n, k):\n",
" old = 0\n",
" young = 1\n",
" total = None\n",
" \n",
" for i in range(1, n + 1):\n",
" total = old + young\n",
" buffer_young = old * k\n",
" old += young\n",
" young = buffer_young\n",
" \n",
" return total"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"5726623061L"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"n_rabbits(34, 2)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment