You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python函数,实现无重复代码查找最长/最短字符串?

方法1:提取通用核心逻辑,传入比较规则

把重复的遍历、更新逻辑抽成一个通用函数,将判断条件作为参数传入,彻底避免代码复制:

def _find_extreme(words, compare_func):
    N = len(words)
    if N == 0:  # 增加空数组判断,避免索引越界
        return None
    extreme = words[0]
    i = 1
    while i < N:
        if compare_func(len(extreme), len(words[i])):
            extreme = words[i]
        i += 1
    return extreme

def find_shortest(words):
    return _find_extreme(words, lambda a, b: a >= b)

def find_longest(words):
    return _find_extreme(words, lambda a, b: a <= b)

如果觉得lambda不够直观,也可以用operator模块的内置比较函数替代:

import operator

def find_shortest(words):
    return _find_extreme(words, operator.ge)  # ge 对应 >=

def find_longest(words):
    return _find_extreme(words, operator.le)  # le 对应 <=

方法2:直接用Python内置的min/max函数(更简洁)

Python内置的min和max支持key参数,能直接根据字符串长度筛选结果,一行代码就能实现需求,完全不用自己写循环:

def find_shortest(words):
    return min(words, key=lambda x: len(x)) if words else None

def find_longest(words):
    return max(words, key=lambda x: len(x)) if words else None

内容的提问来源于stack exchange,提问作者anf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:05:55