Discuss / Python / 习题三 虽然写得不好 但感觉小白都能看懂 分享一下

习题三 虽然写得不好 但感觉小白都能看懂 分享一下

Topic source

# -*- coding: utf-8 -*-

from functools import reduce  #加载reduce函数模块

def strfloat(s):

    f=s.index('.') #确定小数点在字符串中的索引位置

    q=s[:f] #用切片索取小数点前的整数部分

    h=s[f+1:] #用切片索取小数点后的小数部分

    k=len(h)  #获取小数点后的元素个数

    j=q+h   #获得去掉小数点的字符串

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

    def fn(x,y):   #定义一个函数用来将序列变为整数

        return x*10+y

    def chanum(s):  #定义一个函数用来将字符串变为数字

        return dict[s]

    def ding(s):   #定义一个函数用来将获取的整数变为小数

        x=10

        if s==1:

            return x

        while s>1:

            s=s-1

            x=x*10

        return x

    m=reduce(fn,map(chanum,j))#将输入的字符串变为整数

    o=ding(k)  #将小数点补回原位

    return m/o


  • 1

Reply