Skip to content

Instantly share code, notes, and snippets.

@SerpentChris
Created June 5, 2018 14:50
Show Gist options
  • Save SerpentChris/989bae2279f9f25f5602341fee45c085 to your computer and use it in GitHub Desktop.
Save SerpentChris/989bae2279f9f25f5602341fee45c085 to your computer and use it in GitHub Desktop.
terse versions of reduce and defaultdict with no imports
_r = lambda func, lst, first: _r(func, lst[1:], func(first, lst[0])) if lst else first
reduce = lambda func, lst, first=None: _r(func, lst[1:], lst[0]) if first is None else _r(func, lst, first)
_init = lambda self, typ: setattr(self, 'factory', typ)
_get = lambda self, key: dict.__getitem__(self, key) if key in self else dict.__setitem__(self, key, self.factory()) or dict.__getitem__(self, key)
defaultdict = type('defaultdict', (dict,), {'__init__': _init, '__getitem__': _get})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment