Search code examples
pythonlistrandomsample

Sample the neighbour value from a list


Let say, I have a list:

[Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]

and I randomly choose the index (let say idx=4, thus "May"), I want my function to return

[Mar,Apr,May,Jun,Jul]

If the index is 0 (Jan) or 1 (Feb) then I want my function to return [Jan,Feb,Mar,Apr,May]. The length of returned list is always 5.

How to create such function in Python3?

Simple question but why my head starts to explode?

Thanks.


Solution

  • Something like this:

    monthes = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    
    def myfunc(choices, index):
        start = min(max(index - 2, 0), len(choices) - 5)
        return choices[start:start+5]
    
    print(myfunc(monthes, 4))
    print(myfunc(monthes, 0))
    print(myfunc(monthes, 1))