Sleepy
Sleepy

Reputation: 13

Can someone explain how positional arguments in the sort function(key parameter) work?

Python Version:3.8

What I am trying to do:I am trying to write this function that takes a string of words as an input(called sentence) where each word has one number, splits it into a list at each whitespace, loops through every letter in every element, and then returns the number it finds. We then sort the lst variable which has the words of the sentence input as its elements based on the numbers we got. When I run this code I wrote to execute the above steps:

def order(sentence):
    # list of the words in sentence
    lst=sentence.split(' ')
    # nested function that is used as the key argument in the sort method
    def sort_func():
        for i in sentence:
            for j in i:
                if j.isdigit():
                    return j
    # sorting the list
    lst.sort(key=sort_func)
    # returning a string which has the words sorted according to the number we found in each one
    return ' '.join(lst)

I get the following error:

Traceback (most recent call last):
  File "tests.py", line 3, in <module>
    test.assert_equals(order("is2 Thi1s T4est 3a"), "Thi1s is2 3a T4est")
  File "/workspace/default/solution.py", line 12, in order
    lst.sort(key=sort_func)
TypeError: sort_func() takes 0 positional arguments but 1 was given

Now if i replace this line:

def sort_func()

by this:

def sort_func(sentence)

It works and the error is gone.

My question is why is that. I am not convinced. What does positional argument have to do with the code I wrote? I researched how nested functions work to see where the problem was and read about positional arguments, but this still doesn't make sense to me. A detailed explanation of why I got this error is what I want. Thanks in advance.

Upvotes: 0

Views: 170

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45745

This doesn't have anything to do with nested functions. def sort_func(): defines a function that takes zero arguments, but key= expects a function that takes one argument. The error is simply due to that mismatch. The behavior would be identical if sort_func were a top-level, un-nested function like order.

def sort_func(sentence): fixed it because now sort_func accepts a single argument, which means it's usable as a key function.

Upvotes: 3

Related Questions