<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def expand_source_files(filenames, cwd=None):
 """Expand a list of filenames passed in as sources. This is a helper function for handling command line arguments that specify a list of source files and directories. Any directories in filenames will be scanned recursively for .py files. Any files that do not end with ".py" will be dropped. Args: filenames: A list of filenames to process. cwd: An optional working directory to expand relative paths Returns: A list of sorted full paths to .py files """

    out = []
    for f in expand_paths(filenames, cwd):
        if os.path.isdir(f):
            # If we have a directory, collect all the .py files within it.
            out += collect_files(f, ".py")
        else:
            if f.endswith(".py"):
                out.append(f)
    return sorted(set(out))