Discuss / Python / 交作业啦

交作业啦

Topic source

榭柯靳

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

#目标:将字符串'123.456'转化为浮点数123.456

#步骤一:将字符串变为列表

#步骤二:迭代到'.'将列表分为前后两段

#将两段列表分别处理,小数点前与小数点后

#拼接

from functools import reduce

def c(s):

L = list(s)

n = 0

while L[n] != '.':

n = n + 1

list1 = L[:n]

list2 = list(reversed(L[n+1:]))

def char2num(l):

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

return digits[l]

def f1(x,y):

return x * 10 + y

def f2(x,y):

return x  / 10 + y

a = reduce(f1, map(char2num, list1))

b = reduce(f2, map(char2num, list2)) / 10

return a + b

print(c('123.456'))


  • 1

Reply