Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Wednesday, May 8, 2013

Cricket run rate


Problem: Compute current run rate and required run rate for a cricket game. Given: current score, target score, number of overs bowled, total number of overs.

Solution in Python:


from __future__ import division

import math

def calculate_run_rates(current_score, target_score, current_overs, total_overs):
    """

    Author: Mayur P Srivastava

    In overs, fraction part represents number of balls,
    e.g. 5.1, 5.2, 5.3, 5.4, 5.5, 6.0
    """

    current_overs = parse_overs(current_overs)
    total_overs   = parse_overs(total_overs)

    if current_overs > 0:
        current_rr = current_score / current_overs
    else:
        current_rr = 0

    remaining_overs = total_overs - current_overs
    runs_to_win     = target_score - current_score + 1

    required_rr = runs_to_win / remaining_overs


def parse_overs(o):
    completed_overs = math.floor(o)

    balls = math.floor(0.5 + 10 * (o - completed_overs))
    assert balls >= 0 and balls < 6
    
    return completed_overs + balls / 6.0

Concepts Learned: Maths

No comments:

Post a Comment