Николай обнови решението на 15.03.2013 23:37 (преди над 11 години)
+from collections import OrderedDict
+
+#groupby
+
+
+def groupby(func, seq):
+ result = dict()
+ for element in seq:
+ key = func(element)
+ if key not in result:
+ result[key] = list()
+ result[key].append(element)
+ return result
+
+#iterate
+
+
+class Composer:
+ def __init__(self, func, iterations):
+ self.func = func
+ self.iterations = iterations
+
+ def execute(self, operand):
+ result = operand
+ for ind in range(0, self.iterations):
+ result = self.func(result)
+ return result
+
+
+def iterate(func):
+ iteration = 0
+ while True:
+ comp = Composer(func, iteration)
+ iteration = iteration + 1
+ yield lambda x: comp.execute(x)
+
+#zip_with
+
+
+def zip_with(func, *iterables):
+ if(len(iterables) == 0):
+ return iter([])
+ iterators = list()
+ for iterable in iterables:
+ iterators.append(iter(iterable))
+ while True:
+ result = list()
+ for iterator in iterators:
+ result.append(next(iterator))
+ yield func(*result)
+
+#cache
+
+
+class CachedInvoker:
+ def __init__(self, func, cache_size):
+ self.func = func
+ self.cache_size = cache_size
+ self.cache = OrderedDict()
+
+ def invoke(self, *operands):
+ if operands in self.cache:
+ return self.cache[operands]
+ result = self.func(*operands)
+ if self.cache_size > 0:
+ if self.cache_size == len(self.cache):
+ self.cache.popitem(False)
+ self.cache[operands] = result
+ return result
+
+
+def cache(func, cache_size):
+ invoker = CachedInvoker(func, cache_size)
+ return lambda *args: invoker.invoke(*args)