Search code examples
pythonqueue

Calculate the begin time in Python


I have 3 lists,

First list tells me customer name,

cst=[1,2,3,4,5]

Second list tells me its type,

cst_type=['A', 'B', 'B', 'A', 'B']

Third list tell me its arrival,

 arrived_at=[2,5,7,9,10]

After a customer arrives, it needs to be serviced for 3 minutes.

I want to prioritize customers with A type, that is, if A comes and the person(only 1) serving all of them is free or after becoming free, it will give priority to A, otherwise it will work according to FCFS.

How can I make a python program(simple one) to output a list of at what time they begin to be served?

I know if no priority is there then I can use:

For i in range(1,5):
   Service_begin[i]=max(arrival[i], service_end[i-1])

However how to change the program to add priority.


Solution

  • You could build this as a simulation where you progress through the minutes of the day, picking the next customer from two lanes (A and B) based on priorities.

    def serviceOrder(names,types,times):
        serviceDuration = 3
        laneA  = [i for i,t in enumerate(types) if t=="A"] # "A" cutomers (indexes)
        laneB  = [i for i,t in enumerate(types) if t=="B"] # "B" cutomers
        minute = 0 # current minute of the day when server is free
        while laneA or laneB:
            # serve all "A" customers currently present/waiting
            while laneA and times[laneA[0]] <= minute:
                index = laneA.pop(0)
                yield minute,names[index],"A"
                minute += serviceDuration
            # when no As to serve, take one B customer
            if laneB and times[laneB[0]] <= minute:
                index  = laneB.pop(0)
                yield minute,names[index],"B"
                minute += serviceDuration
                continue
            # no customers, wait a minute, and check again
            minute += 1 
    

    note: this assumes that times are in increasing order. You'll need to sort the 3 lists if that's not the case.

    output:

    cst=[1,2,3,4,5]
    cst_type=['A', 'B', 'B', 'A', 'B']
    arrived_at=[2,5,7,9,10]
    for time,name,prio in serviceOrder(cst,cst_type,arrived_at):
        print(time,"...",time+2,"name:",name,prio)
    
    # start...end minute of service, customer name, type
    # 2 ... 4 name: 1 A
    # 5 ... 7 name: 2 B
    # 8 ... 10 name: 3 B
    # 11 ... 13 name: 4 A
    # 14 ... 16 name: 5 B
         
    

    Example with an A customer served before a B customer that arrived earlier:

    cst=[1,2,3,4,5]
    cst_type=['A', 'B', 'A', 'A', 'B']
    arrived_at=[2,3,4,9,10]
    for time,name,prio in serviceOrder(cst,cst_type,arrived_at):
        print(time,"...",time+2,"name:",name,prio)  
    
    # start...end minutes of service, customer name, type    
    # 2 ... 4 name: 1 A
    # 5 ... 7 name: 3 A
    # 8 ... 10 name: 2 B
    # 11 ... 13 name: 4 A
    # 14 ... 16 name: 5 B