Problem 264325 · medium · Level 02 Linear Data Structures

Foxes and Rabbits

py-unpacking · simulation · simultaneous assignment

A valley holds prey rabbits and pred foxes (in hundreds, so the numbers need not be whole). Each season both populations change at the same moment, based on the numbers at the start of the season:

new prey = prey + a * prey - b * prey * pred
new pred = pred + c * prey * pred - d * pred

a is the rabbits' birth rate, b how often a fox catches a rabbit, c how well foxes turn food into cubs and d the foxes' death rate. A population that would drop below zero becomes 0.0.

Write seasons(prey, pred, rates, steps), where rates is the tuple (a, b, c, d), and return the pair (prey, pred) after steps seasons.

Examples

Input:  prey = 10, pred = 5, rates = (0.1, 0.02, 0.01, 0.1), steps = 1
Output: (10.0, 5.0)
Explanation: new prey = 10 + 1 - 0.02 * 50 = 10 and new pred = 5 + 0.5 - 0.5 = 5.
             These numbers are in balance, so they never change.

Input:  prey = 20, pred = 5, rates = (0.1, 0.02, 0.01, 0.1), steps = 2
Output: (19.8, 6.05)
Explanation: Season 1 gives (20.0, 5.5). Season 2: new prey = 20 + 2 - 0.02 * 20 * 5.5 = 19.8
             and new pred = 5.5 + 0.01 * 20 * 5.5 - 0.55 = 6.05, both computed from (20.0, 5.5).

Floats are compared with a tolerance of 1e-6.

Constraints

  • 0 <= prey, pred <= 1000, 0 <= steps <= 1000
  • All rates are between 0 and 1.

Goals

  • Update two variables from their old values in one simultaneous assignment
  • Unpack a tuple of parameters into named variables
  • Recognise the bug where the second update reads an already-updated value
Starting Python…