You need to enable JavaScript to run this app. Python自定义trim()函数(禁内置trim/递归)仅测试用例2不通过求解
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义trim()函数(禁内置trim/递归)仅测试用例2不通过求解

自定义trim函数测试用例2失败的修复方案

需求说明

  • 函数需要实现自定义trim(S)功能:输入字符串S,返回首尾去除空白字符的结果,完整保留字符串中间位置的所有空白字符
  • 实现约束:不允许使用递归逻辑,不允许使用系统内置的trim/rtrim/ltrim类裁剪函数
  • 预期行为示例:
    • trim(' dog ') 返回 'dog'
    • trim(' cat in the hat') 返回 'cat in the hat'
    • trim('')、trim(' ') 均返回空字符串
  • 现有问题:自行编写的函数除测试用例2外,其余所有测试用例均可正常通过

现有实现代码

def trim(S) :
    min_index = 0
    max_index = 0
    if S.isspace() == True:
      new_S = ''
      return new_S
    if len(S) == 0:
      new_S = ''
      return new_S
    for ch in S:
      if ch.isspace() == False and min_index == 0:
        min_index = S.index(ch)
    for ch in S:
      if ch.isspace() == False and S.index(ch) > max_index:
        max_index = S.index(ch)
    new_S = S[min_index:max_index+1]
    return new_S

# 单元测试逻辑
import unittest
class myTests(unittest.TestCase):
 def test1(self):
  self.assertEqual(trim('    dog   '), 'dog')
 def test2(self):
  self.assertEqual(trim('    cat in the hat'), 'cat in the hat')
 def test3(self):
  self.assertEqual(trim(''), '')
 def test4(self):
  self.assertEqual(trim('      '), '')
 def test5(self):
  self.assertEqual(trim(' red green  blue  .'), 'red green  blue  .')

if __name__ == '__main__':
 unittest.main(exit=True)

失败原因分析

原代码在查找最大非空白字符索引时存在两处逻辑错误:

  1. 错误依赖str.index()方法:该方法的作用是返回目标字符第一次出现的索引,而非当前遍历到的字符的实际位置。比如测试用例2的字符串' cat in the hat'中,最后一个非空白字符是末尾的t,但该字符在开头cat的位置已经出现过,S.index('t')只会返回开头t的位置6,无法识别末尾t的实际位置。
  2. 遍历过程未绑定实际索引:循环仅遍历字符内容,没有记录当前字符对应的真实位置,遇到重复字符时无法正确更新最大索引值,最终导致切片时提前截断字符串末尾内容,实际返回结果为'cat in the',与预期不符。

修复实现

调整边界查找逻辑,直接按字符的实际索引定位首尾非空白位置,不再依赖str.index()的返回值:

  1. 优先处理空字符串的边界场景,直接返回空值
  2. 左边界定位:从字符串头部逐位向后检查,记录第一个非空白字符的索引
  3. 右边界定位:从字符串尾部逐位向前检查,记录最后一个非空白字符的索引
  4. 若遍历完成后未找到任何非空白字符(即全空白字符串),直接返回空值
  5. 按照定位到的左右边界执行切片,返回裁剪后的字符串

修复后代码

def trim(S):
    # 空字符串直接返回
    if len(S) == 0:
        return ''
    left = 0
    right = len(S) - 1
    # 定位左边界:跳过开头连续空白
    while left <= right and S[left].isspace():
        left += 1
    # 定位右边界:跳过末尾连续空白
    while right >= left and S[right].isspace():
        right -= 1
    # 全空白场景下left超过right,返回空
    if left > right:
        return ''
    return S[left:right+1]

修复后所有测试用例均可正常通过,字符串中间位置的连续空白会被完整保留,完全符合需求要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.13 14:45:08