Discuss / Python / 第三题比较简单的做法

第三题比较简单的做法

Topic source

韦着选躬

#1 Created at ... [Delete] [Delete and Lock User]
def str2float(s0):
	from functools import reduce
	List1={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'.':0}
	a1=10**(len(s0)-s0.index('.')-1)#字符串长度-小数点位置-小数点占位
	def fn(x,y):
		if y==0:
			return x+y #遇小数点加零,等于忽略小数点
		return x*10+y  #廖老师讲过的str转int方式。
	def Integer(s1):
		return List1[s1]
	return reduce(fn,(map(Integer,s0)))/a1

求问例题里DIGITS和你的答案里List1的作用是什么呀

ClearIight

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

map的作用是传入的函数一次作用到序列的每个元素.

比如传进去的s0是 字符串:'123'

所以 map(Integer, s0), 就是让传进去的字符串中的每个元素(map函数的第二个参数是Iterable, 因此字符串的Iterable的每个元素就是'1','2','3'),    传进Integer函数的元素'1','2','3', 这时就用到了`你问的List1`了.

**通过dict中的key来获取value, 其中key是传入的每个元素'1','2','3', 而获取的value为1, 2, 3. 并且将这三个值通过新的Iterator返回 -> 123**

这就是`List1的作用`

keep11686

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

这里把测试用例换成12340.456的时候 结果不对 

修改了下层主代码 如下

def str2float(s):
    decimal_places: int = len(s) - s.index('.') - 1    
    num_enum = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '0': 0, '.': '.'}
    def fn(x, y) -> int:
        if y != '.':
            return x * 10 + y
        else:
            return x

    return reduce(fn, map(lambda x: num_enum[x], s)) / (10 ** decimal_places)

赞同回复,遇见'.'就跳过执行


  • 1

Reply