1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 
 4 from functools import reduce
 5 
 6 CHAR_TO_INT = {
 7     '0': 0,
 8     '1': 1,
 9     '2': 2,
10     '3': 3,
11     '4': 4,
12     '5': 5,
13     '6': 6,
14     '7': 7,
15     '8': 8,
16     '9': 9
17 }
18 
19 def str2int(s):
20     ints = map(lambda ch: CHAR_TO_INT[ch], s)
21     return reduce(lambda x, y: x * 10 + y, ints)
22 
23 print(str2int('0'))
24 print(str2int('12300'))
25 print(str2int('0012345'))
26 
27 CHAR_TO_FLOAT = {
28     '0': 0,
29     '1': 1,
30     '2': 2,
31     '3': 3,
32     '4': 4,
33     '5': 5,
34     '6': 6,
35     '7': 7,
36     '8': 8,
37     '9': 9,
38     '.': -1
39 }
40 
41 def str2float(s):
42     nums = map(lambda ch: CHAR_TO_FLOAT[ch], s)
43     point = 0
44     def to_float(f, n):
45         nonlocal point
46         if n == -1:
47             point = 1
48             return f
49         if point == 0:
50             return f * 10 + n
51         else:
52             point = point * 10
53             return f + n / point
54     return reduce(to_float, nums, 0.0)
55 
56 print(str2float('0'))
57 print(str2float('123.456'))
58 print(str2float('123.45600'))
59 print(str2float('0.1234'))
60 print(str2float('.1234'))
61 print(str2float('120.0034'))

 

posted on 2017-01-12 15:06  加油AlwaysWin  阅读(2272)  评论(0编辑  收藏  举报