def nest(x, n): a = [] for i in range(n): a.append([x]) return a print nest("hello", 5)
It gives a way out
[['hello'], ['hello'], ['hello'], ['hello'], ['hello']]
Desired Result:
[[[[["hello"]]]]]
Each rotation in a loop that you add to the list. You want to nest the list even more than add more material to it. You could do it something like this:
def nest(x, n): for _ in range(n): x = [x] return x
Each rotation in the loop xcontains a different list wrapped around it.
x
instead of adding you, you can wrap xand call the method recursively until the call number is lessn
n
def nest(x, n): if n <= 0: return x else: return [nest(x, n-1)]
pythonic recursion:
In [8]: def nest(x, n): ...: return nest([x], n-1) if n else x
DEMO:
In [9]: nest(3, 4) Out[9]: [[[[3]]]] In [11]: nest("Stackoverflow", 7) Out[11]: [[[[[[['Stackoverflow']]]]]]]
Source: https://habr.com/ru/post/1657967/More articles:jQuery returns different top and left values ββdepending on the browser - jqueryChrome Adobe Flash Deprecated - google-chromeHow to enable GPS on Android using native response? - react-nativeAvoiding automatic formatting of VSCode while saving from deleting last new line - autoformattingThe structure of the state sample in accordance with the Lisk - oopTurn on GPS automatically, like OLA cabs - androidASP.Net OData not working with SSL termination in LB - asp.netOverride webapi odata link host - asp.netAngular 2 Service Error. Can't find a reason - angularIs there a data structure in Java that can contain 4 or more values ββ- javaAll Articles