Skip to content

Instantly share code, notes, and snippets.

@jackrusher
Created November 11, 2012 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackrusher/4055401 to your computer and use it in GitHub Desktop.
Save jackrusher/4055401 to your computer and use it in GitHub Desktop.
Recursive nesting in Python and Clojure
# N.B. destroys the list; pass a copy if you want to retain the original!
def matryoshka(dolls, depth=1):
out = []
while(len(dolls) > 0):
if dolls[0] == depth:
out.append(dolls.pop(0))
elif dolls[0] > depth:
out.append(matryoshka(dolls, depth+1))
else:
break
return out
matryoshka([1,2,3,3,4,4,2,1])
#[1, [2, [3, 3, [4, 4]], 2], 1]
(defn matryoshka [dolls depth]
(let [[head body] (split-with (partial > (+ 1 depth)) dolls)
[body tail] (split-with (partial < depth) body)]
(concat head (if (not= body ()) (list (matryoshka body (+ 1 depth)))) tail)))
(matryoshka dolls 1)
;; (1 (2 (3 3 (4 4)) 2) 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment