Python高级特性---切片、迭代和列表生成式 相关算法题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_37189082/article/details/100312325

1.利用切片操作,实现一个trim()函数,去除字符串首尾的空格。注意不要调用str的strip()方法。

def trim(s):
    while len(s)>0 and s[:1]==' ':
        s=s[1:] 
    while len(s)>0 and s[-1:]==' ':
        s=s[:-1]
    return s
    
def test_trim():
    assert trim('hello ') == 'hello'
    assert trim(' hello') == 'hello'
    assert trim('hello  ') == 'hello'
    assert trim('  hello') == 'hello'

test_trim()

2.请使用迭代查找一个list中最小和最大值,并返回一个tuple。迭代其实就是for遍历。

def findMinAndMax(L):
    if L==[]:
        return (None,None)
    else:
        min=max=L[0]
        for x in L:
            if x>max:
                max=x
        for y in L:
            if y<min:
                min=y
        return (min,max)

     不使用迭代实现方法

def findMinAndMax(L):
    n = len(L)
    L.sort()
    if n == 0:
        return(None,None)
    else:
        return (L[0],L[n-1])

3.使用列表生成式,将列表中非字符串类型的元素过滤掉,字符串并且小写。

L1 = ['Hello', 'World', 18, 'Apple', None]

结果:['hello', 'world', 'apple']

L2 = [i.lower() for i in L1 if isinstance(i, str)]

 

猜你喜欢

转载自blog.csdn.net/qq_37189082/article/details/100312325
今日推荐