Python / clojure equivalent to NestWhileList math

Impetus: I was looking for something in python that made me

f([1,2,3]) == [[1,2,3], [2,3], [3]]

In clojure, it will be simple (nest rest #(not (empty? %)) lst), or if we had a socket function. We? I'm tired of looking at the clojure api list.

Best approaches in python or clojure would also be appreciated ..

+3
source share
6 answers
data = [1,2,3]
result = [ data[i:] for i in range(len(data)) ]
+3
source

Refund seqs:

user> (take-while seq (iterate rest [1 2 3]))
([1 2 3] (2 3) (3))

Return vectors:

user> (take-while seq (iterate #(subvec % 1) [1 2 3]))
([1 2 3] [2 3] [3])

I saw this template packaged in a function iterate-whilethat is almost the same as your function nest:

(defn iterate-while [pred f x]
  (take-while pred (iterate f x)))

Please note that is (seq x)equivalent, and preferable,(not (empty? x))

+3
source

, - (, , clojure, ):

(take-while identity (iterate next [1 2 3]))

Update:

, , (, [] ..):

(take-whil­e seq (iter­ate rest ...))
+1
user> (reductions conj [] [1 2 3])
([] [1] [1 2] [1 2 3])

. ,

user> (take-while identity (iterate next [1 2 3]))
([1 2 3] (2 3) (3))

user> (rest (reductions conj [] [1 2 3]))
([1] [1 2] [1 2 3])
+1
(partition-all 3 1 [1 2 3])

((1 2 3) (2 3) (3))

(vec (map vec (partition-all 3 1 [1 2 3])))

p.s. 3 1 - [1 2 3] , 3 1 . partition-all , - , 3.

+1

Python:

def f(l):
    while l:
        yield l[:]
        l.pop(0)

([:]) , , . , f.

, .

0

All Articles