Mellow Walk

Consider a list of positive int (zero included). Let’s define a “mellow step” from position i over a list L with the sign s as moving to either:

  • the position resulting from adding L[i] to i if s is 1

  • the position L[i] if s is 0

  • the position resulting from substracting L[i] to i if s is -1

Write the following function in the module with the same name (file mellow_walk.py):

mellow_walk(L, signL, i0)

such that

given

returns

  1. list of the positions visited by a “mellow walk” over L starting at i0 such that each “mellow step” from position i takes the sign from singL[i]. The “mellow walk” ends when either it comes to a position through which it has already walked, or it falls outside the range of L (i.e. including both, positive and negative indexes of a Python list).

  2. int with the position that terminated the mellow walk (this position is not included in the previous list).

For example:


>>> L     = [ 6, -2,  2,  4,  3, -4,  1, -5]
>>> signL = [-1,  0,  1, -1,  0, -1,  1,  0]

>>> mellow_walk(L, signL, 1)
([1, -2, -1, -5], -9)

Observe the resulting list:

  • The first value is 1 because that’s the initial position.

  • The next one is -2 since L[1] is -2 and signL[1] is 0 (i = -2).

  • The next one is -1 since L[-2] is 1 and signL[-1] is 1 (i = -2+1).

  • The next one is -5 since L[-1] is -5 and signL[-1] is 0 (i = -5).

  • Finally, the position -9 is obtained since L[-5] is 4 and signL[-5] is -1 (i = -5-4) which is out of range, hence it does not go into the list but it is the second part of the result.

Doctests are available at the file mellow_walk.test.