python codekatas solutions | Cell 7 | Cell 9 | Search

The max_profit function calculates the maximum possible profit from a list of stock prices by iterating through the list and adding up the differences between each pair of consecutive prices. The function returns 0 as the total profit if the input list is empty, contains only one price, or has prices in descending order.

Cell 8

def max_profit(prices):
    """Find maximum profit possible."""
    profit = 0
    for i in range(len(prices)-1):
        if prices[i+1] > prices[i]:
            profit += prices[i+1] - prices[i]
    return profit

assert max_profit([]) == 0
assert max_profit([100]) == 0
assert max_profit([1,6,5,2,8,1,4,5]) == 15
assert max_profit(range(100, 0, -1)) == 0
print('All passed')

What the code could have been:

def max_profit(prices):
    """
    Find the maximum possible profit from a list of prices.

    Args:
        prices (list): A list of prices where each price is a positive integer.

    Returns:
        int: The maximum possible profit.

    Raises:
        ValueError: If prices is empty or contains non-positive values.
    """
    if not prices:
        raise ValueError("Prices cannot be empty")
    for price in prices:
        if price <= 0:
            raise ValueError("All prices must be positive")
    
    return sum(max(0, prices[i+1] - prices[i]) for i in range(len(prices)-1))

assert max_profit([]) == 0
assert max_profit([100]) == 0
assert max_profit([1,6,5,2,8,1,4,5]) == 15
assert max_profit(range(100, 0, -1)) == 0

# TODO: Implement a more efficient solution using a single pass through the prices list
#       (currently has a time complexity of O(n^2))

Code Breakdown

Function Definition

def max_profit(prices):

Function Documentation

"""Find maximum profit possible."""

Variable Initialization

profit = 0

Loop Through Prices

for i in range(len(prices)-1):

Calculate Profit

if prices[i+1] > prices[i]:
    profit += prices[i+1] - prices[i]

Return Total Profit

return profit

Test Cases

assert max_profit([]) == 0
assert max_profit([100]) == 0
assert max_profit([1,6,5,2,8,1,4,5]) == 15
assert max_profit(range(100, 0, -1)) == 0
print('All passed')