Skip to content

Commit 9c9ef92

Browse files
committed
update reduce sample
1 parent aed8fae commit 9c9ef92

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

samples/functional/do_reduce.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,39 @@ def str2int(s):
2323
print(str2int('0'))
2424
print(str2int('12300'))
2525
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 = -1
44+
def to_float(f, n):
45+
nonlocal point
46+
if n == -1:
47+
point = 0
48+
return f
49+
if point == -1:
50+
return f * 10 + n
51+
else:
52+
point = point + 1
53+
return f + n / pow(10, 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'))

0 commit comments

Comments
 (0)