高效搜索矩阵中连续元素乘积的Python实现

发布于:2024-05-04 ⋅ 阅读:(24) ⋅ 点赞:(0)

在数据分析、图像处理或科学计算等领域,经常需要处理和分析矩阵数据。特别是在寻找矩阵中特定模式或特征时,比如最大乘积的连续元素,可以用于多种应用,从算法交易到机器学习模型的特征工程。Python作为一种强大的编程语言,提供了高效处理这类问题的工具。

import random
from typing import List, Tuple


def create_matrix_list(
    rows: int,
    cols: int,
    randomize: bool = False,
    value_range: Tuple[int, int] = (1, 10),
) -> List[List[int]]:
    """
    Creates and returns a matrix of specified rows and columns.
    If randomize is True, matrix elements will be generated randomly within the specified value_range.
    Otherwise, each element is the current row index multiplied by the number of columns plus the current column index plus one.

    Parameters:
    - rows (int): Number of rows in the matrix.
    - cols (int): Number of columns in the matrix.
    - randomize (bool): Whether to generate matrix elements randomly.
    - value_range (tuple[int, int]): The range of values for generating random elements.

    Returns:
    - list[list[int]]: The generated matrix.
    """
    return [
        [
            random.randint(value_range[0], value_range[1])
            if randomize
            else i * cols + j + 1
            for j in range(cols)
        ]
        for i in range(rows)
    ]


def find_max_prod(matrix: List[List[int]], n: int) -> Tuple[List[int], int, str, dict]:
    """
    Finds the maximum product of n consecutive elements in the given matrix and returns the sequence with the maximum product, the maximum product, the sequence sorted numerically, and the maximum product sequences categorized by direction.

    Parameters:
    - matrix (List[List[int]]): The matrix to search.
    - n (int): The number of consecutive elements.

    Returns:
    - tuple: Contains the sequence with the maximum product, the maximum product, the sequence sorted numerically, and the maximum product information categorized by direction.
    """
    directions = [
        (0, 1, "to the right"),
        (1, 0, "downward"),
        (1, 1, "diagonally down-right"),
        (1, -1, "diagonally down-left"),
    ]
    max_product = float("-inf")
    max_extract = []
    directional_maxes = {
        desc: {"sequence": [], "product": float("-inf"), "sorted_sequence": ""}
        for _, _, desc in directions
    }

    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            for dx, dy, desc in directions:
                if 0 <= i + (n - 1) * dx < len(matrix) and 0 <= j + (n - 1) * dy < len(
                    matrix[0]
                ):
                    extract = []
                    product = 1
                    for x in range(n):
                        element = matrix[i + x * dx][j + x * dy]
                        extract.append(element)
                        product *= element
                    if product > directional_maxes[desc]["product"]:
                        directional_maxes[desc]["sequence"] = extract
                        directional_maxes[desc]["product"] = product
                        directional_maxes[desc]["sorted_sequence"] = "".join(
                            sorted(map(str, extract))
                        )
                        # Update the global maximum product
                        if product > max_product:
                            max_product = product
                            max_extract = extract
                            sorted_max_extract = "".join(sorted(map(str, max_extract)))
    return (
        max_extract,
        max_product,
        sorted_max_extract,
        directional_maxes,
    )


# Sample use
matrix_list = create_matrix_list(15, 15, randomize=True, value_range=(10, 99))
max_extract, max_product, sorted_max_extract, directional_maxes = find_max_prod(
    matrix_list, 2
)

print("Matrix list:")
for row in matrix_list:
    print(row)

print(
    f"\nGlobal maximum product sequence: {max_extract}, Maximum product: {max_product}, Sequence sorted numerically: {sorted_max_extract}"
)
for direction, data in directional_maxes.items():
    print(
        f"{direction} - Maximum product sequence: {data['sequence']}, Maximum product: {data['product']}, Sequence sorted numerically: {data['sorted_sequence']}"
    )
  1. 创建矩阵的函数

文章首先介绍了create_matrix_list函数,它能够根据用户指定的行数、列数、是否随机以及值范围生成一个矩阵。此函数使用了列表推导式,配合random.randint函数,可以选择生成随机数矩阵或者按照特定规则生成矩阵。

  1. 搜索连续元素最大乘积

核心部分find_max_prod函数负责寻找具有最大乘积的连续元素序列。函数定义了四个可能的搜索方向:向右、向下、向右下对角线和向左下对角线。通过遍历每个元素作为起点,检查在每个方向上连续元素的乘积,比较并记录下全局最大乘积和各方向的最大乘积。

  1. 优化策略

优化部分讨论了如何提高搜索效率。首先,通过初始化最大乘积为负无穷大,确保任何正常的乘积值都会被考虑。其次,通过合并全局和各方向最大乘积的计算,减少了重复的计算和比较操作。

  1. 实例和结果

文末提供了一个具体的例子,展示了如何使用这两个函数。通过生成一个15x15的矩阵并寻找最大的两个连续元素的乘积,展示了脚本的实际应用。同时,展示了脚本执行的输出结果,帮助读者更好地理解函数的工作原理和输出。

freeze.png


网站公告

今日签到

点亮在社区的每一天
去签到