Python Code:
Problem – listlib.pairs() - Define a function listlib.pairs()
which accepts a list as an argument, and returns a new list
containing all pairs of elements from the input list. More
specifically, the returned list should (a) contain lists of length
two, and (b) have length one less than the length of the input
list. If the input has length less than two, the returned list
should be empty. Again, your function should not modify the input
list in any way. For example, the function call pairs(['a', 'b',
'c']) should return [['a', 'b'], ['b', 'c']], whereas the call
pairs(['a', 'b']) should return [['a', 'b']], and the calls
pairs(['a']) as well as pairs([]) should return a new empty list.
To be clear, it does not matter what the data type of elements is;
for example, the call pairs([1, 'a', ['b', 2]]) should just return
[[1, 'a'], ['a', ['b', 2]]].
On your own: If this wasn’t challenging enough, how about
defining a generalized operation? Specifically, a function windows
which takes three arguments: a list `, an integer window size w,
and an integer step s. It should return a list containing all
“sliding windows¶” of the size w, each starting s elements after
the previous window. To be clear, the elements of the returned list
are lists themselves. Also, make the step an optional argument,
with a default value of 1. Some examples should clarify what
windows does. First off, the function call windows(x, 2, 1) should
behave identically to pairs(x), for any list x. E.g.,
windows([1,2,3,4,5], 2, 1) should return [[1,2], [2,3], [3,4],
[4,5]]. The function call windows([1,2,3,4,5], 3, 1) should return
[[1,2,3], [2,3,4], [3,4,5]], and the function call
windows([1,2,3,4,5], 2, 3) should return [[1,2], [4,5]]; you get
the idea. Of course, the input list does can contain anything; we
used a few contiguous integers only to make it easier to see how
the output relates to the input. If you prefer a formal definition,
given any sequence x0,x1,...,xN−1, a window size s and a step size
s, the corresponding sliding window sequence w0,w1,... consists of
the the elements defined by wj := [ xjs, xjs+1, ..., xjs+(w−1) ]
for all j such that j ≥0 and js+ w < N.
Python Code: Problem – listlib.pairs() - Define a function listlib.pairs() which accepts a list as an argument, and retu
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
Python Code: Problem – listlib.pairs() - Define a function listlib.pairs() which accepts a list as an argument, and retu
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!