Discuss / Python / 求大神解第三题

求大神解第三题

Topic source

Mr_安生

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

有没有大神能够用这一篇之前所学知识,不要用后面还未学到的知识,把第三题的代码公布一下啊,求教

Mr_安生

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

顶上来··

zyb_826

#3 Created at ... [Delete] [Delete and Lock User]
s = s.split(".",1)
def fn(x,y):
    return x*10+y
def char2num(s):
    digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    return digits[s]
f = reduce(fn,map(char2num,s[0]))+reduce(fn,map(char2num,s[1]))*(0.1**len(s[1]))
return f
x = s.index('.')
n = len(s)-x-1
s = list(s)
del s[x]
ans = reduce(lambda x,y:x*10+y,map(char2num,s))
return ans*(0.1**n)

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

def char2num(s): return DIGITS[s]

from functools import reduce

def str2float(s): def chr2num(s): digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return digits[s]

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

return reduce(fn, map(chr2num, s.replace('.', ''))) / (pow(10, s.rindex('.')))

print('str2float(\'123.456\') =', str2float('123.456')) if abs(str2float('123.456') - 123.456) < 0.00001: print('测试成功!') else: print('测试失败!')

llmr2016

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

我做第三题的时候实在没想到好的方法,用了一个特别笨的方法。 思路:把字符串分解为两部分,第一部分是整数的部分,另一部分是小数点的部分,用if判断字符'.'的位置,然后切片。用两个函数分别处理第一部分。第二部分,然后将两个部分相加,得到最终结果。 这样结果没问题,但是程序特别长,特别难看,要定义四个函数2333

terry-NCL

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

from functools import reduce

def str2float(s): m = s.split('.')

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

def char2num(s):
    digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    return digits[s]

flot1 = reduce(fn, map(char2num, m[0]))
flot2 = reduce(fn, map(char2num, m[1])) / (10 ** len(m[1]))
flot = flot1 + flot2
return flot

Mr_安生

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

感谢各位,但是看给出答案的还是用到了 split index等,看来不然无法解决 小数点的问题

MrBeck_胡

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

可以用索引原数对命令ennumerate +if 命令找到小数点的位置,也就是用多行代码实现index的功能而已

Hello_景尊

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

#!/usr/bin/env python3

-- coding: utf-8 --

#利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:

#在某位同学的基础上改的... from functools import reduce

def str2float(s): a={'1':1,'2':2,'3':3,'4':4,'5':5,'6':6} def check(s): for i in range(len(s)): if s[i] == '.': break return i def opt(s): i=check(s) L=s[:i]+s[i+1:] return L def chksum(s):
return a[s] def fn(x,y): return x10+y app=reduce(fn,map(chksum,opt(s))) def fenmu(s): mu=1 for n in range((len(s)-1-check(s))): mu=10mu return mu return app/fenmu(s)

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


  • 1
  • 2

Reply