Jumped Elements X20478


Statement
 

pdf   zip

Write a function @jumps(a,k)@ that receives a list of strictly positive integers aa and an integer kk, and returns the list of jumped elements in aa starting from position kk.

The list of jumped elements in list aa starting from position kk is defined as the list formed by element a[k] followed by the list of jumped elements starting from position k+a[k]. If kk is larger than the size of aa, the result is an empty list.

For instance, given the list a=a=[2 1 3 5 7 2 9 5 2 4 8] and starting position k=2k=2, the resulting list is [3 2 5]. That is, we start at position k=2k=2 finding element a[k]=3a[k]=3. We advance 33 positions and reach element a[k]=2a[k]=2. We thus advance 22 more positions and land on element a[k]=5a[k]=5. We try to advance 55 positions but reach the end of the list, so we stop.

Sample session

Observations

If you want to test your program locally, remember to include the following lines at the end of the file:

if __name__ == "__main__":
   import doctest
   doctest.testmod(verbose=True)
Sample session
>>> jumps([2, 1, 3, 5, 7, 4, 9, 5, 2, 5, 8], 0)
[2, 3, 4, 5]
>>> jumps([2, 1, 3, 5, 7, 4, 9, 5, 2, 5, 8], 1)
[1, 3, 4, 5]
>>> jumps([2, 1, 3, 5, 7, 4, 9, 5, 2, 5, 8], 3)
[5, 2, 8]
>>> jumps([2, 1, 3, 5, 7, 4, 9, 5, 2, 5, 8], 20)
[]
>>> jumps([2, 1, 3], 1) + jumps([2, 1, 3, 5, 7], 4) 
[1, 3, 7]
Information
Author
ProAl
Language
English
Official solutions
Python
User solutions
Python