Discuss / Python / 第3题,智商低,没什么技巧

第3题,智商低,没什么技巧

Topic source

飞页快刀

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

# 容易看懂的方法

from functools import reduce

def str2float(s):

    def str2int(a):

        DIGITS = {'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 char2num(a):

            return DIGITS[a]

        return reduce(fn, map(char2num, a))

    sp = s.split('.')

    s1 = list(map(str2int, sp))[0]

    s2 = list(map(str2int, sp))[1]

    return s1+s2/10**(len(sp[1]))

print(str2float('123.456'))

print(isinstance(str2float('123.456'), float))

# 不使用split的方法

from functools import reduce

def str2float(s):

    def char2list(s):

        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]

        before = []

        for i in list(map(char2num, s)):

            if i == '.':

                break

            before.append(i)

        remove_list = []

        for i in list(map(char2num, s)):

            if i == '.':

                break

            remove_list.append(i)

        after = []

        for i in list(map(char2num, s)):

            after.append(i)

        for i in remove_list:

            after.remove(i)

        if '.' in after:

            after.remove('.')

        return before,after

    def fn(x,y):

        return x * 10 + y

    s1 =reduce(fn, char2list(s)[0])

    s2= reduce(fn, char2list(s)[1])

    return s1+s2/10**len(char2list(s)[1])

print(str2float('123.456'))

print(isinstance(str2float('123.456'), float))

# 混合整数和小数

from functools import reduce

def change(s):

    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]

    def fn(x,y):

        return x * 10 + y

    if '.' in s:

        def str2float(s):

            def str2int(s):

                return reduce(fn, map(char2num, s))

            sp = s.split('.')

            s1 = list(map(str2int, sp))[0]

            s2 = list(map(str2int, sp))[1]

            return s1+s2/10**(len(sp[1]))

        a = str2float(s)

    else:

        def str2int(s):

            return reduce(fn, map(char2num, s))

        a = str2int(s)

    return a

print(str2float('123.456'))

print(isinstance(str2float('123.456'), float))


  • 1

Reply