Михаил обнови решението на 22.03.2015 19:19 (преди над 9 години)
+from functools import reduce
+
+
+def extract_type(text, t):
+ join = lambda a, b: str(a) + str(b)
+ multiply = lambda pair: str(pair[0]) * pair[1]
+ predicate = lambda pair: isinstance(pair[0], t)
+ return reduce(join, map(multiply, filter(predicate, text)))
+
+
+def reversed_dict(hashmap):
+ return {value: key for key, value in hashmap.items()}
+
+
+def filter_nested_dicts(hashmap):
+ return {k: v for k, v in hashmap.items() if isinstance(v, dict)}
+
+
+def flatten_dict(hashmap):
+ hashmap = hashmap.copy()
+ pairs_with_dict_value = filter_nested_dicts(hashmap)
+ while pairs_with_dict_value:
+ for k in pairs_with_dict_value:
+ for inner_key, inner_value in hashmap[k].items():
+ hashmap[k + '.' + inner_key] = inner_value
+ del hashmap[k]
+ pairs_with_dict_value = filter_nested_dicts(hashmap)
+ return hashmap
+
+
+def filter_complex_keys(hashmap):
+ return {k: v for k, v in hashmap.items() if len(k.split('.')) > 1}
+
+
+def unflatten_dict(hashmap):
+ hashmap = hashmap.copy()
+ to_unflatten = filter_complex_keys(hashmap)
+ while to_unflatten:
+ for k in to_unflatten:
+ innermost = k.split('.')[-1]
+ outer = '.'.join(k.split('.')[:-1])
+ if outer in hashmap:
+ hashmap[outer].update({innermost: hashmap[k]})
+ else:
+ hashmap[outer] = {innermost: hashmap[k]}
+ del hashmap[k]
+ to_unflatten = filter_complex_keys(hashmap)
+ return hashmap
+
+
+def reps(seq):
+ return tuple(filter(lambda x: seq.count(x) > 1, seq))
Тествай extract_type
с крайни случаи. Какво би се случило, ако нямаш елементи от подадения тип?
Хм, не ми е хрумнало, че reduce може да се счупи при празна колекция.