python自学

【Python 3】高级特性

2018-01-05  本文已影响4人  雨水之后

切片

利用切片操作,实现一个trim()函数,去除字符串首尾的空格。

思路:

解法:

def trim(s):
  while s[:1] == ' ':
    s = s[1:]
  while s[-1:] == ' ':
    s = s[:-1]
  return s
    
if trim('hello  ') != 'hello':
    print('测试失败!')
elif trim('  hello') != 'hello':
    print('测试失败!')
elif trim('  hello  ') != 'hello':
    print('测试失败!')
elif trim('  hello  world  ') != 'hello  world':
    print('测试失败!')
elif trim('') != '':
    print('测试失败!')
elif trim('    ') != '':
    print('测试失败!')
else:
    print('测试成功!')

>>> 测试成功!

迭代

使用迭代查找一个list中最小和最大值,并返回一个tuple,不要使用max()min()

思路:

解法:

def minNmax(list):
  if len(list) == 0:
    return (None, None)
  else:
    min = max = list[0]
    for i in list:
      if i < min:
        min = i
      if i > max:
        max = i
    return (min, max)

# 测试
if minNmax([]) != (None, None):
    print('测试失败!')
elif minNmax([7]) != (7, 7):
    print('测试失败!')
elif minNmax([7, 1]) != (1, 7):
    print('测试失败!')
elif minNmax([7, 1, 3, 9, 5]) != (1, 9):
    print('测试失败!')
else:
    print('测试成功!')

>>> 测试成功!

列表生成式

某list1内含字符串、数字及None,通过列表生成式导出一个list2,内含list1内的所有字符串的小写形态。

思路:

解法:

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

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

# 测试:
print(L2)
if L2 == ['hello', 'world', 'apple']:
    print('测试通过!')
else:
    print('测试失败!')

>>> 测试通过!

生成器

一个斐波那契数列生成器。

解法:

def fib(max):
  n, a, b = 0, 0, 1
  while n < max:
    yield b
    a, b = b, a+b
    n += 1
  print('Done!')

f = fib(6)

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

一个杨辉三角形生成器,把每一行看做一个list,用生成器不断输出。

杨辉三角形

思路:

解法:

def triangles():
  l = [1]
  while True:
    yield l
    l = [l[i] + l[i+1] for i in range(len(l)-1)]
    l.insert(0,1)
    l.append(1)

n = 0
results = []
for t in triangles():
    print(t)
    results.append(t)
    n = n + 1
    if n == 10:
        break
if results == [
    [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]
]:
    print('测试通过!')
else:
    print('测试失败!')
    
>>> 测试通过!

THE END.

上一篇 下一篇

猜你喜欢

热点阅读