Roxy
Roxy

Reputation: 127

I am trying to debug python code given but it gives the error as given

I am getting the error as

Traceback:
    in <module>
    in merge_ranges
    TypeError: 'int' object is not iterable

Can someone suggest what is the issue and also for debugging I am using code as

meets = [(1,3),(5,8),(8,14),(13,17)]
print '{} should be {}'.format(merge_ranges(meets))

def merge_ranges(meets):

    #sort by start time
    sorted_meetings = sorted(meets)

    merged_meetings = sorted_meetings[0]

    for current_meeting_start, current_meeting_end in sorted_meetings[1:]:
        last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1]

        if (current_meeting_start <= last_merged_meeting_end):
            merged_meetings[-1] = (last_merged_meeting_start, max(last_merged_meeting_end, current_meeting_end))

        else:
            merged_meetings.append((current_meeting_start, current_meeting_end))
    # write the body of your function here
    return merged_meetings

Upvotes: 1

Views: 63

Answers (3)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

You can't change a tuple as you are in the following two lines:

merged_meetings[-1] = (last_merged_meeting_start, max(last_merged_meeting_end, current_meeting_end)) # here

merged_meetings.append((current_meeting_start, current_meeting_end)) # and here

Tuples are immutatable. Not only are you using a tuple, you are unpacking more values than you should be.

Upvotes: 1

Dectinc
Dectinc

Reputation: 69

You initialized variable merged_meetings as a single tuple, however it should be a list of tuples.

Thus, you have to modify the initialization of merged_meetings to

merged_meetings = [sorted_meetings[0]]

and the result of your testcase will be

[(1, 3), (5, 17)]

Upvotes: 2

havanagrawal
havanagrawal

Reputation: 1039

The problem is in this line:

last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1]

merged_meetings is a tuple, say (1,3).
merged_meetings[-1] is a single value, 3.

You try to unpack 3 to two variables, which is not possible.

Upvotes: 1

Related Questions