python turns strings into Numbers using reduce and map

  • 2020-05-19 05:05:12
  • OfStack

Introduction to reduce and map in python

map(func,seq1[,seq2...]) : apply the function func to each element of a given sequence and provide the return value with a list; If func is None, func is represented as an identity function that returns a list of n tuples containing a collection of elements in each sequence.

reduce(func,seq[,init]) : func function is 2 yuan, will be applied to seq func sequence of elements, each with 1 to (the result of the previous and the next one sequence of elements), under the existing results of continuous and a value effect on the subsequent results, finally reduce our sequence for a single 1 return values: if init given initial value, the first comparison is init and the first sequence elements rather than a sequence of the first two elements.

This article focuses on python's use of reduce and map to convert strings into Numbers.

Problem sets:

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

Solutions and ideas:


from functools import reduce
 
def str2float(s):
 s = s.split('.') # Divide the string into two parts, with the decimal point as the separator 
 
 def f1(x,y): # function 1 , the number before the decimal point is handled by this function 
  return x * 10 + y
 
 def f2(x,y): # function 2 , the number after the decimal point is handled by this function 
  return x / 10 + y
 
 def str2num(str): # function 3 , used to put strings '123' Turn them into Numbers one by one 
  return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[str]
 
 return reduce(f1,map(str2num,s[0])) + reduce(f2,list(map(str2num,s[1]))[::-1])/10
 
 # The last 1 The parts are the essence of the solution 
 # The number before the decimal point '123' with  x * 10 + y  The normal sum will give you that 123 , after the decimal point '456' How do you get that 0.456 ? 
 # First of all, I'm gonna take the string '456' with list(map(str2num,s[1])) into 1 A list of [4,5,6]
 # And then use [::-1] Slice from the back, and the list becomes [6,5,4]
 # Then put the [6,5,4] using reduce Function in f2 In the function, ( 6 / 10 + 5) / 10 + 4 = 4.56 , and get the result 4.56
 # Divided by 1 a 10 , it is concluded that 0.456 , which completes the string successfully '456' It becomes a floating point number 0.456
 # You add them together, you get the final solution, and you get the string '123.456' It becomes a floating point number 123.456

conclusion

The above is the whole content of this article, I hope the content of this article can bring you 1 definite help in learning or using python, if you have any questions, you can leave a message to communicate.


Related articles: