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

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

Към профила на Никола Илиев

Резултати

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

Код

def extract_type(list, wanted_type):
result = ""
for data in list:
if type(data[0]) is wanted_type:
for i in range(data[1]):
result += str(data[0])
return result
def reversed_dict(dictionary):
return dict([(value, key) for key, value in dictionary.items()])
def reps(ds):
return tuple(filter(lambda x: ds.count(x) > 1, ds))
def _flatten_dict_helper(dictionary, parent_dict_key):
result = {}
prefix = parent_dict_key + "." if parent_dict_key else ""
for key, value in dictionary.items():
if type(value) is dict:
result.update(_flatten_dict_helper(value, prefix + key))
else:
result[prefix + key] = value
return result
def flatten_dict(dictionary):
return _flatten_dict_helper(dictionary, None)
def unflatten_dict(dictionary):
result = {}
for key, value in dictionary.items():
nested_keys = key.split(".")
current_dictionary = result
for nested_key in nested_keys:
if nested_key == nested_keys[len(nested_keys) - 1]:
current_dictionary[nested_key] = value
else:
if nested_key not in current_dictionary:
current_dictionary[nested_key] = {}
current_dictionary = current_dictionary[nested_key]
return result

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

...................
----------------------------------------------------------------------
Ran 19 tests in 0.131s

OK

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

Никола обнови решението на 23.03.2015 16:58 (преди над 9 години)

+def extract_type(list, wanted_type):
+ result = ""
+ for data in list:
+ if type(data[0]) is wanted_type:
+ for i in range(data[1]):
+ result += str(data[0])
+ return result
+
+
+def reversed_dict(dictionary):
+ return dict([(value, key) for key, value in dictionary.items()])
+
+
+def reps(ds):
+ return tuple(filter(lambda x: ds.count(x) > 1, ds))
+
+
+def _flatten_dict_helper(dictionary, parent_dict_key):
+ result = {}
+ prefix = parent_dict_key + "." if parent_dict_key else ""
+ for key, value in dictionary.items():
+ if type(value) is dict:
+ result.update(_flatten_dict_helper(value, prefix + key))
+ else:
+ result[prefix + key] = value
+ return result
+
+
+def flatten_dict(dictionary):
+ return _flatten_dict_helper(dictionary, None)
+
+
+def unflatten_dict(dictionary):
+ result = {}
+ for key, value in dictionary.items():
+ nested_keys = key.split(".")
+ current_dictionary = result
+ for nested_key in nested_keys:
+ if nested_key == nested_keys[len(nested_keys) - 1]:
+ current_dictionary[nested_key] = value
+ else:
+ if nested_key not in current_dictionary:
+ current_dictionary[nested_key] = {}
+ current_dictionary = current_dictionary[nested_key]
+ return result