map/reduce

1、

Use the map() function to change the non-standard English name input by the user into uppercase first letter and other lowercase canonical names. Input: ['adam', 'LISA', 'barT'], Output: ['Adam', 'Lisa', 'Bart']:

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

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

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

 

2、

The sum() function provided by Python can accept a list and sum, please write a prod() function that can accept a list and use reduce() to calculate the product:

# -*- coding: utf-8 -*-
from functools import reduce

def prod(L):
    def a(x,y):
        return x*y
    return reduce(a,L)

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('Test succeeded!')
else:
    print('Test failed!')

 

3、

Write a str2float function using map and reduce to convert the string '123.456' to a floating point number 123.456:

# -*- coding: utf-8 -*-
from functools import reduce

def str2float(s):

    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    s = s.split ('.', 1)
    s1 = s[0] # take the integer part
    s2 = s[1] # take the fractional part

    def char2num(n):
        return DIGITS[n]
    m1=reduce(lambda x,y:x*10+y,map(char2num,s1))
    m2=reduce(lambda x,y:x*10+y,map(char2num,s2))
    m3=pow(10,-len(s2)) # For example, pow(10,-3) represents 10 to the power of -3, which is 0.001
    
    return m1 + m2*m3
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('Test succeeded!')
else:
    print('Test failed!')

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325058533&siteId=291194637