Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sliding window over seq

In Clojure, what would be the nicest way to have a sliding window over a (finite, not too large) seq? Should I just use drop and take and keep track of the current index or is there a nicer way I'm missing?

like image 659
pmf Avatar asked Sep 15 '09 15:09

pmf


People also ask

What is sliding window pattern?

A sliding window is a sublist or subarray that runs over an underlying data structure . The data structure is typically iterable and ordered, such as an array or a string . At a high level, you can think of it as a subset of the two pointers method.

How does sliding window algorithm work?

The Sliding Window algorithm is one way programmers can move towards simplicity in their code. This algorithm is exactly as it sounds; a window is formed over some part of data, and this window can slide over the data to capture different portions of it.

Why is it used and what are the advantages of sliding window technique?

The sliding window provides several benefits: It controls the speed of transmission so that no fast sender can overwhelm the slower receiver; It allows for orderly delivery, as we will show; It allows for retransmission of lost frames, specific retransmission policy depends on the specific implementations.

How do I create a sliding window in Python?

Install with pip install sliding_window , and run with from sliding_window import window . You're in for a shock if you think list(window(range(10))) should produce something like [[0,1],[1,2],[2,3],...]


3 Answers

I think that partition with step 1 does it:

user=> (partition 3 1 [3 1 4 1 5 9])
((3 1 4) (1 4 1) (4 1 5) (1 5 9))
like image 64
Jonas Avatar answered Oct 02 '22 02:10

Jonas


If you want to operate on the windows, it can also be convenient to do this with map:

user=> (def a [3 1 4 1 5 9])
user=> (map (partial apply +) (partition 3 1 a))
(8 6 10 15)
user=> (map + a (next a) (nnext a))
(8 6 10 15)
like image 24
Timothy Pratley Avatar answered Oct 02 '22 01:10

Timothy Pratley


I didn't know partition could do this so I implemented it this way

(defn sliding-window [seq length]
  (loop [result ()
         remaining seq]
    (let [chunk (take length remaining)]
      (if (< (count chunk) length)
        (reverse result)
        (recur (cons chunk result) (rest remaining))))))
like image 1
little-dude Avatar answered Oct 02 '22 00:10

little-dude