Калоян обнови решението на 15.03.2013 23:09 (преди над 11 години)
+from functools import reduce
+#from inspect import getargspec
+from collections import OrderedDict
+
+
+def groupby(func, elements):
+ result_dict = {}
+ for element in elements:
+ group = func(element)
+ if not group in result_dict:
+ result_dict[group] = []
+ result_dict[group].append(element)
+ return result_dict
+
+
+def id(x):
+ return x
+
+
+def _compose(func1, func2):
+ return lambda *args, **kwargs: func1(func2(*args, **kwargs))
+
+
+class iterate(object):
+ def __init__(self, function):
+ self.function = function
+ self.func_list = []
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ result = id
+ if len(self.func_list) > 0:
+ result = reduce(_compose, self.func_list)
+ self.func_list.append(self.function)
+ return result
+
+
+def zip_with(func, *iterables):
+ if len(iterables) == 0:
+ return []
+ # Check if the number of iterable lists match the arguments expected
+ #if len(iterables) != len(getargspec(func)[0]):
+ # raise ValueError
+
+ length = len(iterables[0])
+ for it in iterables:
+ if len(it) < length:
+ length = len(it)
+
+ i = 0
+ while i < length:
+ arguments = []
+ for iterable in iterables:
+ arguments.append(iterable[i])
+ yield func(*arguments)
+ i = i + 1
+
+
+class cache(object):
+ def __init__(self, func, cache_size):
+ self._cache = OrderedDict()
+ self._func = func
+ self._size = cache_size
+
+ def __call__(self, *args):
+ if args in self._cache:
+ return self._cache[args]
+ else:
+ if len(self._cache) == self._size:
+ self._cache.popitem(last=False)
+ self._cache[args] = self._func(*args)
+ return self._cache[args]
+
+
+#cache_memory = OrderedDict()
+#
+#def cached_func(func, cache_size, *args):
+# if args in cache_memory:
+# return cache_memory[args]
+# else:
+# if len(cache_memory) == cache_size:
+# cache_memory.popitem(last = False)
+# cache_memory[args] = func(*args)
+# return cache_memory[args]
+#
+#def cache(func, cache_size):
+# return lambda *args: cached_func(func, cache_size, *args)