Решение на Четири функции от Деян Спиров

Обратно към всички решения

Към профила на Деян Спиров

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 20 успешни тест(а)
  • 0 неуспешни тест(а)

Код

def iterate(func):
return FuncIterator(func)
class FuncIterator:
def __init__(self, func):
self.func = func
self.count = 0
def __iter__(self):
return self
def __next__(self):
count = self.count
def res(x):
for i in range(0, count):
x = self.func(x)
return x
self.count += 1
return res
def groupby(func, seq):
result = dict()
for i in seq:
key = func(i)
if key in result:
result[key].append(i)
else:
result[key] = [i]
return result
def zip_with(func, *iterables):
return map(lambda params: func(*params), zip(*iterables))
def cache(func, cache_size):
func_calls = list() # contains (params, result) tuples
def func_cached(*current_params):
for (old_params, old_result) in func_calls:
if old_params == current_params:
return old_result
result = func(*current_params)
func_calls.append((current_params, result))
if len(func_calls) > cache_size:
del func_calls[0]
return result
return func_cached

Лог от изпълнението

....................
----------------------------------------------------------------------
Ran 20 tests in 0.014s

OK

История (1 версия и 1 коментар)

Деян обнови решението на 14.03.2013 21:12 (преди над 11 години)

+
+
+def iterate(func):
+ return FuncIterator(func)
+
+
+class FuncIterator:
+ def __init__(self, func):
+ self.func = func
+ self.count = 0
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ count = self.count
+
+ def res(x):
+ for i in range(0, count):
+ x = self.func(x)
+ return x
+ self.count += 1
+ return res
+
+
+def groupby(func, seq):
+ result = dict()
+ for i in seq:
+ key = func(i)
+ if key in result:
+ result[key].append(i)
+ else:
+ result[key] = [i]
+ return result
+
+
+def zip_with(func, *iterables):
+ return map(lambda params: func(*params), zip(*iterables))
+
+
+def cache(func, cache_size):
+ func_calls = list() # contains (params, result) tuples
+
+ def func_cached(*current_params):
+ for (old_params, old_result) in func_calls:
+ if old_params == current_params:
+ return old_result
+
+ result = func(*current_params)
+ func_calls.append((current_params, result))
+ if len(func_calls) > cache_size:
+ del func_calls[0]
+ return result
+
+ return func_cached