Problem one: The use of the map () function, the user input of the non-standard English name, the first letter capitalized, other lowercase canonical name. Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart ']
Question two: the sum () function provided by Python can accept a list and sum, write a prod () function, accept a list and use the reduce () to calculate the product
Problem three: Write a str2float function using map and reduce to convert the string ' 123.456 ' to a floating-point number 123.456
#-*-coding:utf-8-*- fromFunctoolsImportReduce"""usage of the map function: def f (x): Return x*xprint map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) output results: [1, 4, 9, 10, 25, 36, 49, 64, 81] f (x) = x * x││┌───┬───┬───┬───┼───┬───┬───┬───┐││││││││ │ [1 2 3 4 5 6 7 8 9]││││││││││││ ││││││ [1 4 9 16 25 36 49 64 81] using the map () function, you can convert a list to another list, you only need to pass in the conversion function--------------------------------------------------------------------the reduce () function accumulates elements in the parameter sequence. The function uses all the data in a data collection (linked list, tuple, and so on) to perform the following operations on the function function (with two parameters) passed to reduce, which first operates on the 1th and 2 elements of the set, and the resulting results are then calculated with the third data using the functions, and finally a result is obtained. 。 """#Q1 uses the map () function to change the non-canonical English name entered by the user into the first capitalization and the other lowercase canonical names. Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart ']defNormalize (L):returnList (Map (LambdaName:str.title (name), L)) #Q1 Method TwodefLower2upper (L):returnMapLambdaS:s[0:1].upper () + s[1:].lower (), L)#Q2 python provides a sum () function that accepts a list and sums it, write a prod () function that accepts a list and uses the reduce () to calculate the productdefprod (L):returnReduceLambdaX, Y:x *y, L)#Q3 uses map and reduce to write a str2float function that converts the string ' 123.456 ' to a floating-point number 123.456DIGITS = {'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9'8 {}defChar2num (s):#convert strings to numbers returnDigits[s]deffn (x, y):#transform a sequence into an integer returnX*10 +ydefStr2float (s): F_before= S.split ('.') [0]#number before the decimal pointF_end = S.split ('.') [1]#number after the decimal point returnReduce (FN, map (Char2num, F_before)) + reduce (FN, map (Char2num, f_end))/1000#Test TypePrint(Str2float ('123.456'))
Use of the map () and reduce () functions in Python3