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

高效查找最长字母顺序子串:代码优化与PEP 8合规方案问询

最长字母序子串代码优化方案

7-8行PEP 8规范代码示例

这段代码遵循PEP 8命名规范,用简洁的迭代逻辑实现核心功能:

def longest_alpha_sub(s):
    longest, current = s[0], s[0]
    for a, b in zip(s, s[1:]):
        current = current + b if a <= b else b
        longest = current if len(current) > len(longest) else longest
    return longest

print(longest_alpha_sub('zabcabcd'))  # 输出: abcd

职场适用写法(约16行)

侧重可读性、健壮性和可维护性,适配团队协作场景:

def find_longest_alphabetical_substring(input_str: str) -> str:
    """查找字符串中最长的按字母顺序排列的子串
    
    参数:
        input_str: 待处理的输入字符串
        
    返回:
        最长的字母顺序子串;若输入为空则返回空字符串
    """
    if not input_str:
        return ""
    
    longest_sub = current_sub = input_str[0]
    
    for idx in range(len(input_str) - 1):
        current_char, next_char = input_str[idx], input_str[idx+1]
        current_sub = current_sub + next_char if current_char <= next_char else next_char
        if len(current_sub) > len(longest_sub):
            longest_sub = current_sub
    
    return longest_sub

# 测试执行
test_str = 'zabcabcd'
print(f"输入'{test_str}'的最长字母序子串: '{find_longest_alphabetical_substring(test_str)}'")

PEP 8合规性点评

对比原代码,优化后的写法在以下方面符合PEP 8规范:

  • 变量命名:使用longest_sub、current_sub这类蛇形命名(snake_case),替代原代码的混合命名风格,符合Python变量命名约定。
  • 迭代逻辑:用zip(s, s[1:])直接遍历相邻字符对,替代原代码的索引遍历,更贴合Python的迭代式编程习惯。
  • 注释规范:避免冗余的“说明动作”型注释(如原代码的# Loop through string.),职场写法使用文档字符串(docstring)明确函数功能、参数和返回值,符合PEP 257规范。
  • 边界处理:加入空字符串判断,避免原代码在输入为空时触发索引错误,符合健壮性要求。
  • 代码简洁性:用三元表达式简化条件赋值,避免重复分支代码,同时保持可读性。

75字符内单行写法

s='zabcabcd';l=c=s[0];for a,b in zip(s,s[1:]):c=c+b if a<=b else b;l=c if len(c)>len(l) else l;print(l)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:20:41