Discuss / Python / 练习

练习

Topic source

skychi

#1 Created at ... [Delete] [Delete and Lock User]
def normalize(name):
    def str2format(s):
        if isinstance(s, str):
            if len(s) == 0:
                return s
            return s[:1].upper() + s[1:].lower()
        raise TypeError('bad operand type')
    return list(map(str2format, name))


print(normalize(['adam', 'LISA', 'barT', 'A', ' ', '']))


def prod(l):
    def multiplier(x, y):
        return x * y
    if not l:
        raise TypeError('bad operand type')
    if isinstance(l, list):
        return reduce(multiplier, l)
    raise TypeError('bad operand type')


print('[1, 2, 3, 4, 5]的积为', prod([1, 2, 3, 4, 5]))
print('[0, 1, 2, 3, 4]的积为', prod([0, 1, 2, 3, 4]))
print('[3, 5, 7, 9]的积为', prod([3, 5, 7, 9]))


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

def str2float(s):

    def f(x, y):
        return x * 10 + y

    def char2number(t):
        return DIGITS[t]

    if isinstance(s, str):
        # 使用'.'分割字符串
        sl = s.split('.')
        integer_part = reduce(f, map(char2number, sl[0]))
        if s.rfind('.') == -1:
            return integer_part
        decimal_part = reduce(f, map(char2number, sl[-1])) * pow(10, -len(sl[-1]))
        return integer_part + decimal_part
    raise TypeError('bad operand type')


print('\'123.456\'转化为浮点数为', str2float('123.456'))
print('\'123\'转化为浮点数为', str2float('123'))

skychi

#2 Created at ... [Delete] [Delete and Lock User]
def str2float(s):
    def f(x, y):
        return x * 10 + y

    def char2number(t):
        return DIGITS[t]

    if isinstance(s, str):
        # 是否含有'.'
        if s.rfind('.') == -1:
            return reduce(f, map(char2number, s))
        # 使用'.'分割字符串
        sl = s.split('.')
        integer_part = reduce(f, map(char2number, sl[0]))
        decimal_part = reduce(f, map(char2number, sl[-1])) * pow(10, -len(sl[-1]))
        return integer_part + decimal_part
    raise TypeError('bad operand type')

  • 1

Reply