Last active
October 2, 2017 01:51
-
-
Save SpikeXy/ffca5d8578b2e6a557f18d5c482f4d6f to your computer and use it in GitHub Desktop.
Map.Reduce #python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> from functools import reduce | |
>>> def fn(x, y): | |
... return x * 10 + y | |
... | |
>>> 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] | |
... | |
>>> reduce(fn, map(char2num, '13579')) | |
13579 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> from functools import reduce | |
>>> def add(x, y): | |
... return x + y | |
... | |
>>> reduce(add, [1, 3, 5, 7, 9]) | |
25 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> def f(x): | |
... return x * x | |
... | |
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) | |
>>> list(r) | |
[1, 4, 9, 16, 25, 36, 49, 64, 81] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
def str2int(s): | |
def fn(x, y): | |
return x * 10 + y | |
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] | |
return reduce(fn, map(char2num, s)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 str2int(s): | |
return reduce(lambda x, y: x * 10 + y, map(char2num, s)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment