Discuss / Python / 新手交作业

新手交作业

Topic source

冬凉默殇

#1 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from functools import reduce

def char2num(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):
    l = list(s)
    index = s.find('.')
    if index != -1: 
        t = len(l) - index - 1 
        del l[index]
    else:
        t = 0 

    return reduce(lambda x, y: x * 10 + y, map(char2num, l))/pow(10, t)

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

  • 1

Reply