PyProgram #4 – Who is on duty ?

We had an interesting problem posed in python mailing list, though it is not a very tough one. But still, practical problems are a fun to solve. This guy wanted to know how he can find which group is on duty. There are 4 group of fire-fighters each cycled on duty for a day one after another. Poor guys, they do not get any off even for holidays. The 4 groups all joined on a single day, so the start day is common for all. Based on this starting day, we have to find which group is on duty if given a particular day. This is a simple and interesting problem to solve. So, we all jumped in and used the datetime module. Here is my code,

#!/usr/bin/env python
"""Data Cycle Finder
Find which group takes charge on a corresponding date.
There are four groups, each working on a 24-hour cycle
one after another. The groups work one day after another
in order, without any break for holidays.

Given a date, it is needed to find which group is on
duty. All the groups have a start date and a group
number. Hence given a date, the output should be the
group number which is on duty.

The input date is of the form dd/mm/yyyy.

from datetime import date
import sys

def dutyfinder(_date):
    start = date(2007,1,1) # the duty cycle started on 1st jan 2007
    return (date.toordinal(_date)-date.toordinal(start))%4

inputdate = sys.argv[1]
indate = sys.argv[1].split('/')
enddate = date(int(indate[2]),int(indate[1]),int(indate[0]))
onduty = int(dutyfinder(enddate)) + 1
print "The group to report for duty on %s is %s" %(str(inputdate),str(onduty))

Now, we need to call this file with the input date as the argument. The starting date is set to 1st January 2007 and the input date format is dd/mm/yyyy. To find which group should report to duty on 10.01.2007,

$ python 10/01/2007
The group to report for duty on 10/01/2007 is 2

I had mailed the OP the code and he has thanked me for it 😉


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s