""" Your task is to write a function that adds one to every number in a nested data structure. The nested data structure can be a list or dict, and each nested position can be a list, dict, int, str, or bool. In the event that a nested position is a list or dict there can be many levels of nesting but not so many to prohibit implementing the solution recursively :) I've provided a few test cases for your implementation that should pass at the end of this session IMPORTANT NOTE: This function should be entitled 'add1' """ nested_list = [1, dict(2=[1,2,3], "a"=["b", dict(c=4)]), True] expected_nested_list_transformed = [2, dict(3=[2,3,4], "a"=["b", dict(c=5)]), True] nested_dict = dict(ca=dict(sfbay=[415, 650]), il=dict(chicago=[224, 773, 847])) expected_nested_dict_transformed = dict(ca=dict(sfbay=[416, 651]), il=dict(chicago=[225, 774, 848])) def add1(ds): if isinstance(ds, list): return [add1(i) for i in ds] elif isinstance(ds, dict): return {add1(k): add1(v) for (k,v) in ds.items()} elif isinstance(ds, int): return ds + 1 elif isinstance(ds, (bool, str)): return ds else: # Technically not needed return ds assert add1(nested_list) == expected_nested_list_transformed assert nested_list[0][2][0] == 2 assert add1(nested_dict) == expected_nested_dict_transformed assert nested_dict['ca']['sfbay'] == [415, 650]
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question