Решение на Пет малки функции от Йордан Канчелов

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

Към профила на Йордан Канчелов

Резултати

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

Код

import collections
def extract_type(collection, elem_type):
return (''.join([elem[0] * elem[1]
for elem in collection if type(elem[0]) is elem_type]))
def reversed_dict(dic):
return dict(map(lambda a: [a[1], a[0]], dic.items()))
def reps(input):
return tuple(([x for x in input if input.count(x) > 1]))
def flatten_dict(d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten_dict(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
def unflatten_dict(dictionary):
result_dict = dict()
for key, value in dictionary.items():
parts = key.split(".")
d = result_dict
for part in parts[:-1]:
if part not in d:
d[part] = dict()
d = d[part]
d[parts[-1]] = value
return result_dict

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

...................
----------------------------------------------------------------------
Ran 19 tests in 0.149s

OK

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

Йордан обнови решението на 23.03.2015 16:40 (преди над 9 години)

+import collections
+
+
+def extract_type(collection, elem_type):
+ return (''.join([elem[0] * elem[1]
+ for elem in collection if type(elem[0]) is elem_type]))
+
+
+def reversed_dict(dic):
+ return dict(map(lambda a: [a[1], a[0]], dic.items()))
+
+
+def reps(input):
+ return tuple(([x for x in input if input.count(x) > 1]))
+
+
+def flatten_dict(d, parent_key='', sep='.'):
+ items = []
+ for k, v in d.items():
+ new_key = parent_key + sep + k if parent_key else k
+ if isinstance(v, collections.MutableMapping):
+ items.extend(flatten_dict(v, new_key, sep=sep).items())
+ else:
+ items.append((new_key, v))
+ return dict(items)
+
+
+def unflatten_dict(dictionary):
+ result_dict = dict()
+ for key, value in dictionary.items():
+ parts = key.split(".")
+ d = result_dict
+ for part in parts[:-1]:
+ if part not in d:
+ d[part] = dict()
+ d = d[part]
+ d[parts[-1]] = value
+ return result_dict