Решение на Пет малки функции от Никола Шахпазов

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

Към профила на Никола Шахпазов

Резултати

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

Код

def extract_type(arr, typ):
"""Joins into a string only elements of a particular type.
Keyword arguments:
arr -- an array of tuples (val, repetitions)
typ -- the type to be extracted
"""
return ''.join(''.join([str(x[0])] * x[1])
for x in arr if type(x[0]) == typ)
def reversed_dict(dictionary):
"""Reverses keys with values in a dictionary."""
return {v: k for k, v in dictionary.items()}
def flatten_dict(dictionary, accum_key = ''):
"""Flattens a nested dictionary."""
result = {}
for current_key, value in dictionary.items():
key = accum_key + current_key
if isinstance(value, dict):
result.update(flatten_dict(value, key + '.'))
else:
result[key] = value
return result
def unflatten_dict(obj):
"""Produces a dictionary from a flattened one."""
result = {}
for key, value in obj.iteritems():
keys = key.split('.')
current = result
for part in keys[:-1]:
if part not in current:
current[part] = {}
current = current[part]
current[keys[-1]] = value
return result
def reps(arr):
"""Removes elements which are unique in the tuple."""
result = []
for i, v in enumerate(arr):
if v in arr[i+1:] or v in result:
result += [v]
return tuple(result)

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

...................
----------------------------------------------------------------------
Ran 19 tests in 0.159s

OK

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

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

+def extract_type(arr, typ):
+ """Joins into a string only elements of a particular type.
+ Keyword arguments:
+ arr -- an array of tuples (val, repetitions)
+ typ -- the type to be extracted
+ """
+ return ''.join(''.join([str(x[0])] * x[1])
+ for x in arr if type(x[0]) == typ)
+
+
+def reversed_dict(dictionary):
+ """Reverses keys with values in a dictionary."""
+ return {v: k for k, v in dictionary.items()}
+
+def flatten_dict(dictionary, accum_key = ''):
+ """Flattens a nested dictionary."""
+ result = {}
+ for current_key, value in dictionary.items():
+ key = accum_key + current_key
+ if isinstance(value, dict):
+ result.update(flatten_dict(value, key + '.'))
+ else:
+ result[key] = value
+ return result
+
+
+def unflatten_dict(obj):
+ """Produces a dictionary from a flattened one."""
+ result = {}
+ for key, value in obj.iteritems():
+ keys = key.split('.')
+ current = result
+ for part in keys[:-1]:
+ if part not in current:
+ current[part] = {}
+ current = current[part]
+ current[keys[-1]] = value
+ return result
+
+def reps(arr):
+ """Removes elements which are unique in the tuple."""
+ result = []
+ for i, v in enumerate(arr):
+ if v in arr[i+1:] or v in result:
+ result += [v]
+ return tuple(result)