do_reduce.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from functools import reduce
  4. CHAR_TO_INT = {
  5. '0': 0,
  6. '1': 1,
  7. '2': 2,
  8. '3': 3,
  9. '4': 4,
  10. '5': 5,
  11. '6': 6,
  12. '7': 7,
  13. '8': 8,
  14. '9': 9
  15. }
  16. def str2int(s):
  17. ints = map(lambda ch: CHAR_TO_INT[ch], s)
  18. return reduce(lambda x, y: x * 10 + y, ints)
  19. print(str2int('0'))
  20. print(str2int('12300'))
  21. print(str2int('0012345'))
  22. CHAR_TO_FLOAT = {
  23. '0': 0,
  24. '1': 1,
  25. '2': 2,
  26. '3': 3,
  27. '4': 4,
  28. '5': 5,
  29. '6': 6,
  30. '7': 7,
  31. '8': 8,
  32. '9': 9,
  33. '.': -1
  34. }
  35. def str2float(s):
  36. nums = map(lambda ch: CHAR_TO_FLOAT[ch], s)
  37. point = 0
  38. def to_float(f, n):
  39. nonlocal point
  40. if n == -1:
  41. point = 1
  42. return f
  43. if point == 0:
  44. return f * 10 + n
  45. else:
  46. point = point * 10
  47. return f + n / point
  48. return reduce(to_float, nums, 0.0)
  49. print(str2float('0'))
  50. print(str2float('123.456'))
  51. print(str2float('123.45600'))
  52. print(str2float('0.1234'))
  53. print(str2float('.1234'))
  54. print(str2float('120.0034'))