Discuss / Python / 交作业

交作业

Topic source

倚叠如山

#1 Created at ... [Delete] [Delete and Lock User]

两种思路:

思路一,把空格切掉:

def trim(s):
    while s != '' and s[0] == ' ':
        s = s[1:]
    while s != '' and s[-1] == ' ':
        s = s[:-2]

    return s

思路二,把非空格字符提取出来:

def trim(s):
    length = len(s)
    left = 0
    right = length - 1
    
    while length > left and s[left] == ' ' :
        left = left + 1
    
    while right > 0 and s[right] == ' ' :
        right = right - 1
    
    return s[left:right+1]

这个好啊,简单易懂

王不留行

#3 Created at ... [Delete] [Delete and Lock User]

思路1中:

s = s[:-2]

应该改为:

s = s[:-1]

原代码一次切去了末尾2个字符,对于末尾只有一个空格的场景会出错。

换言之,廖老师给出的测试代码覆盖不全面,缺少一个'hello '的测试用例。


  • 1

Reply