Created
November 11, 2012 16:21
-
-
Save jackrusher/4055401 to your computer and use it in GitHub Desktop.
Recursive nesting in Python and Clojure
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
# 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] |
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
(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