Discuss / Python / 练习

练习

Topic source

###1

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

def normalize(name):
    return name.capitalize()

L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

###2

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

from functools import reduce
from collections import Iterable

def prod(L):
    if not isinstance(L,Iterable):
        raise TypeError('Parameter must be iterable')
    return reduce(lambda a,b:a*b,L)

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))

###3

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

from functools import reduce


def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]


def str2float(s):
    if not isinstance(s, str):
        raise TypeError('Parameter must be str')
    if '.' not in s:
        return int(s)
    int_str, float_str = s.split('.')
    return reduce(lambda x, y: x * 10 + y, map(char2num, int_str + float_str)) / (10 ** len(float_str))


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

  • 1

Reply