Discuss / Python / 用递归最简单

用递归最简单

Topic source

遥望君山

#1 Created at ... [Delete] [Delete and Lock User]
def trim(s):
    if s == '' or s[0] != ' ' and s[-1] != ' ':
        return s
    if s[0] == ' ':
        return trim(s[1:])
    if s[-1] == ' ':
        return trim(s[:-1])

测试的一个结果:这里应该用到了短路,把s==‘’放前面可以解决

elif trim('') != '':
    print('测试失败!')

报错问题

遥望君山

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

还可以继续简化

def trim(s):
    if s == '' or ' ' not in s[0]+s[-1]:
        return s
    if s[0] == ' ':
        return trim(s[1:])
    return trim(s[:-1])

贝朵不分

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

def trim(s):

l=len(s)

if l==0:

return s

if s[0]=='  ':

s=s[1:l]

return trim(s)

if s[-1]=='  ':

s=s[0:-2]

return trim(s)

return s

测试通过


  • 1

Reply