2

Hw would you get a list of 12-month numbers from 3 months back from the current month? For example:

The current month is Feb = 2 (month number)

So 3 months back is Nov = 11 (month number)

so the list should be [11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I have done:

month_choices = deque([1, 2,3,4,5,6,7,8,9,11,12])
month_choices.rotate(4)
Harry
  • 13,091
  • 29
  • 107
  • 167

3 Answers3

4

Can the user specify the current month?

If so:

current_month = 2

[(i - 4) % 12 + 1 for i in range(current_month, current_month + 12)]

Otherwise, replace the first line with the following:

current_month = int(datetime.datetime.today().strftime('%m'))

That said, it would probably be better to use datetime.timedelta for any form of date manipulation.

gmds
  • 19,325
  • 4
  • 32
  • 58
0
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
def fun(current_month,month_back):
    a=[]
    index = l.index(current_month)
    a=l[index-month_back:]+l[:index-month_back] # list slicing take the values from month back to the end of year and from the start of the list to month back 
    return a
print(fun(2,3))
# output : [11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

If you really want to rotate an array, there are generally two ways to do this. The first is more pythonic and involves appending the end of the list to the front. The second way is to utilize the collections library and rotate a list wrapped in a deque object.

''' Rotate an array of elements
'''

from collections import deque
from datetime import datetime

# Approach #1
def rotate_1(arr, amount):
    return arr[amount:] + arr[:amount]  # append the front of the list to the back

# Approach #2
def rotate_2(arr, amount):
    shifted = deque(arr)                # wrap list in an deque
    shifted.rotate(amount * -1)         # rotate normally works left-to-right
    return list(shifted)                # unwrap the list

months = list(range(1, 13))             # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

if __name__ == '__main__':
    offset = datetime.now().month - 1   # 1 (curent month indexed at 0)
    months = rotate_2(months, offset)   # [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1]
    months = rotate_2(months, -3)       # [11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(months)
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132