v9.1.1
Menu

Array Slicing

easyFREESubsetting, Slicing, IndexingNumPy SlicingNumpy

Problem Statement

Extract portions of a NumPy array using slicing syntax.

Background

NumPy slicing: arr[start:stop:step]

  • start: Starting index (inclusive, default 0)
  • stop: Ending index (exclusive)
  • step: Step size (default 1)

Your Task

Write a function slice_array(arr) that returns a dictionary with:

  • "first_three": First 3 elements as list
  • "last_three": Last 3 elements as list
  • "every_other": Every other element as list
  • "reversed": Reversed array as list

Output Format

Return a dictionary with exactly these four keys.

Example

Input
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Output
{'first_three': [0, 1, 2], 'last_three': [7, 8, 9], 'every_other': [0, 2, 4, 6, 8], 'reversed': [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]}
Reasoning
  • arr is a 1D array of n=10n = 10 integers. Write aia_i for the element at position ii, counting from 0; here ai=ia_i = i, so every value is also its own position.
  • first_three keeps positions 0,1,20, 1, 2, giving [0, 1, 2]. last_three keeps positions n−3,n−2,n−1=7,8,9n-3, n-2, n-1 = 7, 8, 9, giving [7, 8, 9].
  • every_other keeps the even positions i=2ki = 2k with 2k<n2k < n: 0,2,4,6,80, 2, 4, 6, 8, giving [0, 2, 4, 6, 8]. It always starts with the first element, so for an odd nn the last element is kept too (5 elements give positions 0, 2, 4).
  • reversed fills output position jj with input position n−1−jn-1-j: j=0j=0 takes a9=9a_9 = 9 and j=9j=9 takes a0=0a_0 = 0, giving [9, 8, 7, 6, 5, 4, 3, 2, 1, 0].
  • Each value is a plain list of integers, so the printed dictionary shows bare square brackets.
  • Notice that when n=3n = 3, first_three and last_three are the same three elements, because the two windows overlap completely.

Constraints

  • Array will have at least 3 elements
  • Use slicing syntax arr[start:stop:step]

Learn this in

More from Numpy

solution.py

Test results

Sign in to run your code against the test cases.