Discuss / Python / 作业

作业

Topic source

livedevil

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

写了好久……第三题 本来很长的,调试完后可以用lambda一步一步缩减成最短 ps.from math import pow,省了一个def power

from functools import reduce
from math import pow
def chr2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2float(s):
    return reduce(lambda x,y:x*10+y,map(chr2num,s.replace('.','')))/pow(10,len(s)-s.find('.')-1)
print(str2float('985.64785'))

请问作业题在哪里看啊

2012Flyer

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

from functools import reduce from math import pow def chr2num(s): return {'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0}[s] def str2float(s): if s.find('.')!=-1: pointstation=pow(10,len(s)-1-s.find('.')) else: pointstation=1.0 return reduce(lambda x,y:x*10+y,map(chr2num,s.replace('.','')))/pointstation

print(str2float('0')) print(str2float('123.456')) print(str2float('123.45600')) print(str2float('0.1234')) print(str2float('.1234')) print(str2float('120.0034'))

2012Flyer

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

增加判断语句是为了下面这句

print(str2float('120'))

2012Flyer

#5 Created at ... [Delete] [Delete and Lock User]
在此插入代码

缩减一下

from functools import reduce from math import pow def chr2num(s): return {'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0}[s] def str2float(s): ''' if s.find('.')!=-1: pointstation=pow(10,len(s)-1-s.find('.')) else: pointstation=1.0 ''' return reduce(lambda x,y:x*10+y,map(chr2num,s.replace('.','')))/(pow(10,len(s)-1-s.find('.')) if s.find('.')!=-1 else 1.0)

print(str2float('120')) print(str2float('0')) print(str2float('123.456')) print(str2float('123.45600')) print(str2float('0.1234')) print(str2float('.1234')) print(str2float('120.0034'))


  • 1

Reply