找出数组里最大元素和最小元素

必应出来的一段参考代码(ref:How 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) -> 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

你可能感兴趣的:(python)