Решение на Пет малки функции от Илиан Стаменов

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

Към профила на Илиан Стаменов

Резултати

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

Код

from functools import reduce
from collections import Counter
def extract_type(types, typed):
return reduce(lambda x, y: x + y, map(lambda x: str(x[0]) * x[1],
filter(lambda x: type(x[0]) is typed, types)), "")
def reversed_dict(dict):
return {y: x for x, y in dict.items()}
def reps(elements):
return tuple(x for x in elements if Counter(elements)[x] > 1)
def flatten_dict(dic):
for i in list(dic.keys()):
if type(dic[i]) is dict:
flatten_dict(dic[i])
for j in dic[i].keys():
dic[".".join([i, j])] = dic[i][j]
del dic[i]
return dic
def unflatten_dict(dic):
if(type(dic) is dict):
for i in list(dic.keys()):
if i.find(".") is not -1:
(key, value) = i.split('.', 1)
if not dic.get(key):
dic[key] = dict([(value, dic[i])])
else:
dic[key].update({value: dic[i]})
unflatten_dict(dic[key])
del dic[i]
return dic

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

...................
----------------------------------------------------------------------
Ran 19 tests in 0.190s

OK

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

Илиан обнови решението на 22.03.2015 22:14 (преди над 9 години)

+from functools import reduce
+from collections import Counter
+
+
+def extract_type(types, typed):
+ return reduce(lambda x, y: x + y, map(lambda x: str(x[0]) * x[1],
+ filter(lambda x: type(x[0]) is typed, types)), "")
+
+
+def reversed_dict(dict):
+ return {y: x for x, y in dict.items()}
+
+
+def reps(elements):
+ return tuple(x for x in elements if Counter(elements)[x] > 1)
+
+
+def flatten_dict(dic):
+ for i in list(dic.keys()):
+ if type(dic[i]) is dict:
+ flatten_dict(dic[i])
+ for j in dic[i].keys():
+ dic[".".join([i, j])] = dic[i][j]
+ del dic[i]
+ return dic
+
+
+def unflatten_dict(dic):
+ if(type(dic) is dict):
+ for i in list(dic.keys()):
+ if i.find(".") is not -1:
+ (key, value) = i.split('.', 1)
+ if not dic.get(key):
+ dic[key] = dict([(value, dic[i])])
+ else:
+ dic[key].update({value: dic[i]})
+ unflatten_dict(dic[key])
+ del dic[i]
+ return dic