Discuss / Python / 第三题

第三题

Topic source

泪语花

#1 Created at ... [Delete] [Delete and Lock User]

# -*- coding: utf-8 -*-

from functools import reduce

def str2float(s):
    n = 0
    for ch in s :
        if ch == '.' :
            index = n
            break
        n = n + 1
    s = s[0:n] + s[n + 1 : len(s)]
    def char2num(L) :
         return{'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[L]
    def fn(x,y) :
         return x * 10 + y
    return  reduce(fn,map(char2num,s))/ pow(10,len(s) - n -1)

print('str2float(\'123.456\') =', str2float('123.456'))

受拼接字符串的启发= =

泪语花

#2 Created at ... [Delete] [Delete and Lock User]
pow(10,len(s) - n -1)这里多减了一个1= =

  • 1

Reply