-
杨辉三角
1 2 3 4 5 6 7 8 9 10 11 12
def triangles(): L = [1] while 1: yield L L.append(0) L = [L[i-1] + L[i] for i in range(len(L))] n = 0 for t in triangles(): print(t) n = n + 1 if n == 10: 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]
-
字符串转浮点数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
from functools import reduce def str2float(s): def s2n(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': -1}[s] nums = list(map(s2n, s)) if -1 in nums: dot_index = nums.index(-1) nums.remove(-1) else: dot_index = len(nums) return reduce(lambda x, y: x + y, map(lambda x: x * 10 ** (dot_index - nums.index(x) - 1), nums)
验证
1 2 3 4 5 6
print(str2float('0')) print(str2float('123.456')) print(str2float('123.45600')) print(str2float('0.1234')) print(str2float('.1234')) print(str2float('120.0034'))
结果有点奇葩, 改日再看
1 2 3 4 5 6
0 123.456 123.456 0.12340000000000001 # 囧 0.12340000000000001 120.0034
加载评论