Discuss / Python / 作业

作业

Topic source

lostanother

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

第一题

def normalize(name):
    return name[0].upper()+name[1:].lower()

第二题

    def f(x,y):
      return x*y
    return reduce(f,L)

lostanother

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

第三题

def str2float(s):
    n = len(s)-s.index('.')-1
    s = s[:s.index('.')]+s[s.index('.')+1:]
    def char2int(s):
      return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    def f(x,y):
      return 10*x+y
    return reduce(f,map(char2int,s))/pow(10,n)

想了半天,最后还是先看了楼上诸位才写出来的。写的过程中产生个疑问,想请教下为什么pow(0.1,3)算出来的结果会是0.0010000002这样的数字呢?

lostanother

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

又改进了一下

from functools import reduce

def str2float(s):
    n = 0
    try:
      n = len(s)-s.index('.')-1
      s = s[:s.index('.')]+s[s.index('.')+1:]
    except:
      pass
    def char2int(s):
      return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    def f(x,y):
      return 10*x+y
    return reduce(f,map(char2int,s))/pow(10,n)

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

  • 1

Reply