本文介绍: 如果数组元素很多,则需切片生成器,以免占用过多内存

必应出来的一段参考代码refHow to Use Hypothesis and Pytest for Robust Property-Based Testing in Python | Pytest With Eric):

def find_largest_smallest_item(input_array: list) -> tuple:  
    """  
    Function to find the largest and smallest items in an array  
    :param input_array: Input array  
    :return: Tuple of largest and smallest items  
    """  
  
    if len(input_array) == 0:  
        raise ValueError  
    # Set the initial values of largest and smallest to the first item in the array  
    largest = input_array[0]  
    smallest = input_array[0]  
  
    # Iterate through the array  
    for i in range(1, len(input_array)):  
        # If the current item is larger than the current value of largest, update largest  
        if input_array[i] > largest:  
            largest = input_array[i]  
        # If the current item is smaller than the current value of smallest, update smallest  
        if input_array[i] < smallest:  
            smallest = input_array[i]  
  
    return largest, smallest 

简洁一点的:

def find_bigest_smallest_item(input_array: list) -&gt; tuple:
    if not input_array:
        raise ValueError
    big = small = input_array[0]
    for v in input_array[1:]:
        if v > big:
            big = v
        elif v < small:
            small = v
    return big, small

如果数组元素很多,则需切片生成器,以免占用过多内存

from itertools import islice

def find_bigest_smallest_item(input_array: list) -> tuple:
    if not input_array:
        raise ValueError
    big = small = input_array[0]
    for v in islice(input_array, 1, len(input_array)):
        if v > big:
            big = v
        elif v < small:
            small = v
    return big, small

原文地址:https://blog.csdn.net/jaket5219999/article/details/134752954

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_31550.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注