去除字符串首尾的空格

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def trim(s):
    if s[:1] != ' ':			#当字符串开头没有空格后,开始判断结尾是否为空格
        if s[-1:] != ' ':
            return s
        else:
            return trim(s[:-1])
    else:						#先对字符串开头是否含有空格进行判断
        return trim(s[1:])

    print(trim('  h  '))
    print(trim('      '))

查找一个list中最小和最大值,并返回一个tuple

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def min_max(s):
    if len(s) == 0:					#首先判断list是否为空
        return(None, None)
    else:
        big = s[0]
        for n in s:					#利用for循环先判断最大值
            if big < n:
                big = n
            else:
                pass
        small = s[0]
        for n in s:					#同样用for循环找出最小值
            if small > n:
                small = n
            else:
                pass
        return(small, big)

    print(min_max([1, 4, 6, 9, -1, 10, 0, 13]))

将L1中的字符转换为小写并输出(排除非字符串类型)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def test(s):
    l = []
    for n in s:
        if isinstance(n, str):			#先对字符串中的字符进行类型判断
            l.append(n.lower())			#对字符型的数据进行lower处理并添加进l列表
        else:
            pass
    return(l)

    L1 = ['Hello', 'World', 18, 'Apple', None]
    print(test(L1))

斐波拉契数列(generator:生成器)

斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:1, 1, 2, 3, 5, 8, 13, 21, 34, …

1
2
3
4
5
6
7
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b				#‘=’号右边的值a,b是当前还未进行赋值的a,b值
        n = n + 1
    return 'done'

生成器(generator)法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield (b)					#将print替换成yield就编程generator了
        a, b = b, a + b
        n = n + 1
    return('done')

    g = fib(10)
    while True:
        try:
            x = next(g)
            print('g:', x)
        except StopIteration as e:		#捕获StopIteration错误
            print('Generator return value:', e.value)	#返回值包含在StopIteration的value中
            break

杨辉三角

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def triangles(m):
    a = [1]
    n = 1
    while n <= m:
        yield a
        a = [1]+[a[i]+a[i+1] for i in range(len(a)-1)]+[1]
        n = n + 1

    g = triangles(10)
    while True:
        try:
            x = next(g)
            print('g:', x)
        except StopIteration as e:
            print('Generator return value:', e.value)
            break

输出结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]