import itertools
import random


def select_item(items_with_profit_ratio):

    """Given a list of tuples of the form (item_index, item_profitability_ratio, item), select an item proportionally to its profitability ratio, and return its index"""

    # find the cumulative profitability ratios, code based on random.choices() from the standard library of Python
    cumulative_profit_ratios = list(itertools.accumulate(item_with_profit_ratio[1] for item_with_profit_ratio in items_with_profit_ratio))
    profit_ratio_sum = cumulative_profit_ratios[-1]

    # randomly select a ratio within the range of the sum
    profit_ratio = random.uniform(0, profit_ratio_sum)

    # find the value that lies within the random ratio selected; binary search code is based on bisect.bisect_left from standard Python library, but adapted to profitability ratio check
    lowest = 0
    highest = len(items_with_profit_ratio)
    while lowest < highest:
        middle = (lowest + highest) // 2
        if cumulative_profit_ratios[middle] <= profit_ratio:
            lowest = middle + 1
        else:
            highest = middle

    return lowest