Home > Net >  Python3: I'm Trying to merge two list in the func that my professor gave me but it just never o
Python3: I'm Trying to merge two list in the func that my professor gave me but it just never o

Time:09-24

def mergedSchedules(pers1Schedule, pers2Schedule):
    merged =[]
    i,j =0,0
    while i < len(pers1Schedule) and j< len(pers2Schedule):
        meeting1, meeting2 =pers1Schedule[i], pers2Schedule[j]
        if meeting1[0]<= meeting2[0]:
            merged.append(meeting1)
            i =1
        else:
            merged.append(meeting2)
            j =1
    while i< len(pers1Schedule):
        merged.append(meeting1)
        i =1
    while i< len(pers2Schedule):
        merged.append(meeting2)
        j =1
    return merged

pers1Schedule = [['0:00', '9:00'], ['7:00', '8:30'], ['12:00', '13:00'], ['16:00', '18:00'], ['19:00', '23:59']]
pers2Schedule = [['0:00', '9:00'], ['9:00', '10:30'], ['12:20', '14:30'], ['14:00', '15:00'], ['16:00', '17:00'], ['18: 30', '23:59']]

mergedSchedules(pers1Schedule, pers2Schedule)

It works if i use small list but it doesn't when the list is bigger i dont know if i can change the code for the func since its given by the professor but its not working.

CodePudding user response:

In order to sort the merged list you really need the times (I assume that's what they are) to be normalised - i.e. HH:MM

So, with appropriately normalised data, you can do this:-

def merge(l1, l2):
    rv = l1.copy()
    for e in l2:
        if e not in rv:
            rv.append(e)
    return sorted(rv, key=lambda x: (x[0], x[1]))

pers1Schedule = [['00:00', '09:00'], ['07:00', '08:30'], ['12:00', '13:00'], ['16:00', '18:00'], ['19:00', '23:59']]
pers2Schedule = [['00:00', '09:00'], ['09:00', '10:30'], ['12:20', '14:30'], ['14:00', '15:00'], ['16:00', '17:00'], ['18:30', '23:59']]

print(merge(pers1Schedule,pers2Schedule))

CodePudding user response:

pers1Schedule = [['0:00', '9:00'], ['7:00', '8:30'], ['12:00', '13:00'], ['16:00', '18:00'], ['19:00', '23:59']] pers2Schedule = [['0:00', '9:00'], ['9:00', '10:30'], ['12:20', '14:30'], ['14:00', '15:00'],['16:00', '17:00'],['18: 30', '23:59']]

list1=[pers2Schedule[0:3]]

list3=pers1Schedule list1

print(list3)

  • Related