sombrero
sombrero

Reputation: 41

Finding a different way to solve python problem

So, my assignment this week for my coding class is to solve the problem of The Best Time to Party (Here's the pdf explaining the assignment The Best Time To Party) . I have already figured out the code for the problem, but I'm confused on Exercise 2 where it asks me to find an alternative way that doesn't depend on the granularity of time. I'm not sure how to solve this, and could I get some help with it? Thank you!

My code for the original problem is below.

sched = [(6, 8), (6, 12), (6, 7), (7, 8), (7, 10), (8, 9), (8, 10), (9, 12),(9, 10), (10, 11), (10, 12), (11, 12)]
sched2 = [(6.0, 8.0), (6.5, 12.0), (6.5, 7.0), (7.0, 8.0), (7.5, 10.0), (8.0, 9.0),(8.0, 10.0), (9.0, 12.0), (9.5, 10.0), (10.0, 11.0), (10.0, 12.0), (11.0, 12.0)]


def bestTimeToPartySmart(schedule, start, end):

    times = []
    for c in schedule:
        times.append((c[0], 'start'))
        times.append((c[1], 'end'))


    sortlist(times)

    maxcount, time = chooseTimeConstrained(times, start, end)

    print ('Best time to attend the party is at', time,\
           'o\'clock', ':', maxcount, 'celebrities will be attending!')
    


def sortlist(tlist):
    for index in range(len(tlist)-1):
        ismall = index
        for i in range(index, len(tlist)):
            if tlist[ismall][0] > tlist[i][0] or \
               (tlist[ismall][0] == tlist[i][0] and \
                tlist[ismall][1] > tlist[i][1]):
                ismall = i
        tlist[index], tlist[ismall] = tlist[ismall], tlist[index]
    
    return


def chooseTimeConstrained(times, start, end):

    rcount = 0
    maxcount = 0
    time = 0
    
    for t in times:
        if t[1] == 'start':
            rcount = rcount + 1
        elif t[1] == 'end':
            rcount = rcount - 1
        if rcount > maxcount and t[0] >= start and t[0] < end:
            maxcount = rcount
            time = t[0]

    return maxcount, time


bestTimeToPartySmart(sched2, 10.0, 12.0)
    

Upvotes: 1

Views: 63

Answers (1)

Mike67
Mike67

Reputation: 11342

Based on the pdf, the idea is to check each celebrity arrival and determine how many other celebrities are already at the party when the celebrity arrives. When you find the max count, you should arrive with that celebrity.

Here's some pseudo-code to clarify:

max = 0
beststarttime = None

For each celeb:  # check each celeb arrival time
   cnt=0
   for each otherceleb:  # check other celebrities already at the party
       if celeb.starttime in (otherceleb.starttime....otherceleb.endtime):
           cnt+=1
   if cnt > max: 
       max = cnt
       beststarttime = celeb.starttime  # you arrive with this celebrity

I would get there at 6 pm because that's when Beyoncé arrives. :)

Upvotes: 1

Related Questions