Act fast, special offers end soon! Up to $294 is savings when you get Premium today.
Get offer codes

Dont need to call a function?

In the below code, after we def a function, dont we need to call out the function when we used it? but in the below, we did not call out a function, and how can it return the answer?

Screen Link: https://app.dataquest.io/m/354/regular-expression-basics/8/negative-character-classes

My Code:

def first_10_matches(pattern):
    """
    Return the first 10 story titles that match
    the provided regular expression
    """
    all_matches = titles[titles.str.contains(pattern)]
    first_10 = all_matches.head(10)
    return first_10

pattern=r'[jJ]ava[^sS]'
java_titles=titles[titles.str.contains(pattern)]

What I expected to happen:
I expect the code be or someway to call a function
selected_pattern= titles(first_10_matches(pattern)) java_titles=titles[titles.str.contains(pattern)]

The function was provided to us in case we’d like to check if our pattern is correct before continuing with the rest of the code. It’s a good time saving practice when you work with a big data set (it’s faster to find 10 first matches than process a whole dataset).
The code for calling the function would be:
first_10_matches(pattern)
Or
first_10 = first_10_matches(pattern)
In case you want to assign the result to a variable

1 Like

I agree with you; it’s faster to find 10 rather than process the whole dataset. But take a look at the code for this helper function:

def first_10_matches(pattern):
    """
    Return the first 10 story titles that match
    the provided regular expression
    """
    all_matches = titles[titles.str.contains(pattern)]
    first_10 = all_matches.head(10)
    return first_10

This function does both! It does return only the first 10 matches but in order to do this, it first must find them all. See variable all_matches in the code above.

1 Like

You are so right. I have to admit that I hadn’t pay much attention to the code if the function. Anyway, according to the dq explanation the function is offered to us so that we could test our regex before continuing with the rest of the code.

Yes, exactly! I like helper functions…they help! :laughing: