educative.io

Task Scheduler - unable to pass > 1 arg to sorted() (Python)

Hi there,

I am confused why I am getting this error given that the solution has the sorted() method being passed 2 args?

    Traceback (most recent call last):
  File "/usercode/./__edu__exec.py", line 30, in <module>
    actual_output = user_function(*input)
  File "/usercode/main.py", line 11, in least_time
    sorted_task_freqs = {task: freq for task, freq in sorted(task_freqs.items(), lambda x: x[1])}
TypeError: sorted expected 1 argument, got 2

Here is my code:

from collections import defaultdict

def least_time(tasks, n):
    # count and store frequencies of tasks
    task_freqs = defaultdict(int)
    for task in tasks:
        task_freqs[task] += 1
    num_unique_tasks = len(task_freqs)
    
    # sort by frequencies (values)
    sorted_task_freqs = {task: freq for task, freq in sorted(task_freqs.items(), lambda x: x[1])}

    # start scheduling tasks in desc order & compute idle time
    total_idle_time = 0
    num_tasks_left = len(tasks)
    while num_tasks_left > 0:
        idle_time = n + 1 # add 1 to account for the first task having to be completed first
        for i in range(num_unique_tasks):
            if sorted_task_freqs[i] > 0:
                sorted_task_freqs[i] -= 1
                idle_time -= 1
                num_tasks_left -= 1
            else:
                break
        if num_tasks_left > 0:
            total_idle_time += idle_time

    # total time = sum(num of tasks + idle time)
    return len(tasks) + total_idle_time



----
Course: https://www.educative.io/courses/grokking-coding-interview-patterns-python
Lesson: https://www.educative.io/courses/grokking-coding-interview-patterns-python/task-scheduler
1 Like

Hello @Sean_Bivins,

Let me help you debug the issue with the error. As the compiler says, the error is occurring because the sorted function is being called incorrectly. The sorted function should take only 1 argument, In your solution it takes an iterable and returns a new sorted list, but it seems like you are trying to use it with a lambda function, which is causing the error.

To fix this issue, you should use the key parameter of the sorted function to specify the sorting criterion. Here’s the corrected line:

sorted_task_freqs = {task: freq for task, freq in sorted(task_freqs.items(), key=lambda x: x[1])}

This change uses the key parameter to tell sorted to sort based on the second element of each tuple (the frequency in this case). The lambda function lambda x: x[1] extracts the second element of the tuple for sorting.

This will fix the issue with the sorted function. Hope this clears your confusion regarding the error you’re encountering. Feel free to share any more suggestions and feedbacks, we’d happy to help.

Happy learning!

1 Like