from functools import partial from bisect import insort """ demonstrating reduce with simple functions """ # start with an iterable nums = map(lambda x: x+1, range(10)) # and a binary function (with some type restraints) add = lambda a, b: a + b prod = lambda a, b: a * b pair = lambda a, b: (a, b) print reduce(add, nums, 0) # print reduce(prod, nums, 1) # print reduce(pair, nums, 0) # let's try to sort # reduce let's us think of just a single step without worrying about the recursion stuff # insort inserts an element in sorted order, reduce lets us expand insort into a full sort def insert_sorted(_list, elem): insort(_list, elem) return _list # print reduce(insert_sorted, [2, 6, 8, 3, 4, 153, 8, 1], []) """ demonstrating partial and reduce by building a nested dictionary accessor """ letters = { "1": {"11": {"111": "a"}, "12": {"121": "b", "122": "c"}}, "2": {"21": {"211": "d"}, "22": {"221": "e", "222": "f"}} } # print reduce(dict.__getitem__, ["1"], letters) # print reduce(dict.__getitem__, ["2", "21", "211"], letters) def rdce(iterable, base, func): """ allows reduce to take **kwargs """ return reduce(func, iterable, base) access = partial(rdce, func=dict.__getitem__) # print access(["1"], letters) # print access(["1", "12"], letters) from_letters = partial(access, base=letters) # print from_letters(["1", "12", "121"]) # print from_letters(["2", "22", "221"]) # for troubleshooting, there is a bug in access # which we will discover when using from_letters # print from_letters(["2", "22", "3"])
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question