Created
November 21, 2017 12:47
-
-
Save kgourgou/72df7cfedced19356b6912ba399e356f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from scipy import clip | |
def dict_clipper(dictionary): | |
""" | |
Clips all the numeric values of a dictionary so | |
that they lie within [0,1]. | |
It recurses within inner dictionaries, | |
if any. | |
>>> A = {"B":-5, "C":{"D":10000, "F":0.3}} | |
>>> dict_clipper(A) | |
>>> print(A) | |
{"B":0, "C":{"D":1, "F":0.3}} | |
""" | |
for key in dictionary: | |
if isinstance(dictionary[key], numbers.Number): | |
dictionary[key] = clip(dictionary[key], 0, 1) | |
elif isinstance(dictionary[key], dict): | |
dict_clipper(dictionary[key]) | |
else: | |
raise ValueError(f"Cannot recognise dictionary[{key}]") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment