Discuss / Python / 虽然有点啰嗦,不过也是自己的思路测试成功,还是很高兴的

虽然有点啰嗦,不过也是自己的思路测试成功,还是很高兴的

Topic source

似水年华_

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

d = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}

def ch(s): return d[s]

def sum(x,y): return x * 10 + y

def str2float(s): S = s.split('.') s1 = S[0] s2 = S[1] n = [] m = len(s2) for i in map(ch, s2): n.append(i / (10 ** m)) h = reduce(sum,map(ch,s1)) q = reduce(sum,n) return h + q

写完后,看你的写法 才知道str有split方法。分割后取len也是个不错的方法,可以间接获取‘.’的位置。你的思路是小数点前后分开,我写的时候,前面并没有分。只要s去掉‘.’后操作,完成后除以10的(小数点后位数的)次方就可以了。以下是参考您的做法: from functools import reduce DIGITS={'0':1,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}

def str2num(s): return DIGITS[s]

def fn(x,y): return x*10+y

def str2float(s): S=s.split('.') s1=S[0] s2=S[1] n=len(s2) return (reduce(fn,map(str2num,s1+s2)))/(10**n)

以及我最开始自己的写法: from functools import reduce DIGITS={'0':1,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}

def str2num(s): return DIGITS[s]

def fn(x,y): return x*10+y

def str2float(s): n=0 for ch in s[::-1]: if ch=='.': break n=n+1

#print('n=',n)
#‘.’所在的索引号
index=len(s)-n-1
#print('index=',index)
#    去掉‘.’的新字符串
l=s[:index]+s[index+1:]

#print('l=',l)

total=reduce(fn,map(str2num,l))
#print('total=',total)
return total/(10**n)

似水年华_

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

我的方法比较啰嗦,你的比较简洁


  • 1

Reply