Python itertools.filterfalse() Examples

The following are 30 code examples for showing how to use itertools.filterfalse(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module itertools , or try the search function .

Example 1
Project: PolarSeg   Author: edwardzhou130   File: lovasz_losses.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mean(l, ignore_nan=False, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = ifilterfalse(isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == 'raise':
            raise ValueError('Empty mean')
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 2
Project: QCElemental   Author: MolSSI   File: itertools.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    # straight from the docs, https://docs.python.org/3/library/itertools.html#itertools-recipes
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in itertools.filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element 
Example 3
Project: ext_portrait_segmentation   Author: clovaai   File: lovasz_losses.py    License: MIT License 6 votes vote down vote up
def mean(l, ignore_nan=False, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = ifilterfalse(isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == 'raise':
            raise ValueError('Empty mean')
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 4
Project: SegmenTron   Author: LikeLy-Journey   File: lovasz_losses.py    License: Apache License 2.0 6 votes vote down vote up
def mean(l, ignore_nan=False, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = ifilterfalse(isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == 'raise':
            raise ValueError('Empty mean')
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 5
Project: centerpose   Author: tensorboy   File: losses.py    License: MIT License 6 votes vote down vote up
def mean(l, ignore_nan=False, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = ifilterfalse(isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == 'raise':
            raise ValueError('Empty mean')
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 6
Project: Particle-Cloud-Framework   Author: capitalone   File: elb.py    License: Apache License 2.0 6 votes vote down vote up
def _need_update(curr_list, desired_list):
    """
    Checks to see if there are any difference in curr_list or desired_list. If they are different this returns True.

    Args:
        curr_list (list): list of dictionaries
        desired_list (list): list of dictionaries

    Returns:
         bool
    """
    #Checks if items need to be added or removed.
    add = list(itertools.filterfalse(lambda x: x in curr_list, desired_list))
    remove = list(itertools.filterfalse(lambda x: x in desired_list, curr_list))
    if add or remove:
        return True
    return False 
Example 7
Project: Particle-Cloud-Framework   Author: capitalone   File: alb.py    License: Apache License 2.0 6 votes vote down vote up
def _need_update(self, curr_list, desired_list):
        """
        Checks to see if there are any difference in curr_list or desired_list. If they are different this returns True.

        Args:
            curr_list (list): list of dictionaries
            desired_list (list): list of dictionaries

        Returns:
            bool
        """
        #Checks if items need to be added or removed.
        add = list(itertools.filterfalse(lambda x: x in curr_list, desired_list))
        remove = list(itertools.filterfalse(lambda x: x in desired_list, curr_list))
        if add or remove:
            return True
        return False 
Example 8
Project: Particle-Cloud-Framework   Author: capitalone   File: dynamodb_table.py    License: Apache License 2.0 6 votes vote down vote up
def _need_update(self, curr_list, desired_list):
        """
        Checks to see if there are any differences in curr_list or desired_list. If they are different True is returned.

        Args:
            curr_list (list): list of dictionaries
            desired_list (list): list of dictionaries

        Returns:
             bool
        """
        # Checks if items need to be added or removed.
        add = list(itertools.filterfalse(lambda x: x in curr_list, desired_list))
        remove = list(itertools.filterfalse(lambda x: x in desired_list, curr_list))
        if add or remove:
            return True
        return False 
Example 9
Project: rich   Author: willmcgugan   File: segment.py    License: MIT License 6 votes vote down vote up
def filter_control(
        cls, segments: Iterable["Segment"], is_control=False
    ) -> Iterable["Segment"]:
        """Filter segments by ``is_control`` attribute.

        Args:
            segments (Iterable[Segment]): An iterable of Segment instances.
            is_control (bool, optional): is_control flag to match in search.

        Returns:
            Iterable[Segment]: And iterable of Segment instances.
        
        """
        if is_control:
            return filter(attrgetter("is_control"), segments)
        else:
            return filterfalse(attrgetter("is_control"), segments) 
Example 10
Project: LightNet   Author: ansleliu   File: utils.py    License: MIT License 6 votes vote down vote up
def mean(l, ignore_nan=False, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = filterfalse(np.isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == 'raise':
            raise ValueError('Empty mean')
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 11
Project: vgraph   Author: bioinformed   File: iterstuff.py    License: Apache License 2.0 6 votes vote down vote up
def unique_everseen(iterable, key=None):
    """List unique elements, preserving order. Remember all elements ever seen.

    >>> ''.join(unique_everseen('AAAABBBCCDAABBB'))
    'ABCD'
    >>> ''.join(unique_everseen('ABBCcAD', str.lower))
    'ABCD'

    """
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element 
Example 12
def mean(l, ignore_nan=False, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = ifilterfalse(isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == 'raise':
            raise ValueError('Empty mean')
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 13
Project: pytorch_segmentation   Author: yassouali   File: lovasz_losses.py    License: MIT License 6 votes vote down vote up
def mean(l, ignore_nan=False, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = ifilterfalse(isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == 'raise':
            raise ValueError('Empty mean')
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 14
Project: hangar-py   Author: tensorwerk   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def unique_everseen(iterable, key=None):
    """List unique elements, preserving order. Remember all elements ever seen.

    >>> list(unique_everseen('AAAABBBCCDAABBB'))
    ['A', 'B', 'C', 'D']
    >>> list(unique_everseen('ABBCcAD', str.lower))
    ['A', 'B', 'C', 'D']
    """
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element 
Example 15
Project: pytorch-tools   Author: bonlime   File: lovasz.py    License: MIT License 6 votes vote down vote up
def mean(l, ignore_nan=False, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = filterfalse(isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == "raise":
            raise ValueError("Empty mean")
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n


# --------------------------- Convinient classes --------------------------- 
Example 16
Project: pennylane   Author: XanaduAI   File: base.py    License: Apache License 2.0 6 votes vote down vote up
def _op_descendants(self, op, only):
        """Descendants of the given operator in the quantum circuit.

        Args:
            op (Operator): operator in the quantum circuit
            only (str, None): the type of descendants to return.

                - ``'G'``: only return non-observables (default)
                - ``'O'``: only return observables
                - ``None``: return all descendants

        Returns:
            list[Operator]: descendants in a topological order
        """
        succ = self.circuit.descendants_in_order((op,))
        if only == "O":
            return list(filter(_is_observable, succ))
        if only == "G":
            return list(itertools.filterfalse(_is_observable, succ))
        return succ 
Example 17
Project: Efficient-Segmentation-Networks   Author: xiaoyufenfei   File: lovasz_losses.py    License: MIT License 6 votes vote down vote up
def mean(l, ignore_nan=False, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = ifilterfalse(isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == 'raise':
            raise ValueError('Empty mean')
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 18
Project: virgin-media-hub3   Author: KarlJorgensen   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def unique_everseen(iterable, key=None):
    """List unique elements, preserving order.

    Remember all elements ever seen

    >>> list(unique_everseen('AAAABBBCCDAABBB'))
    ['A', 'B', 'C', 'D']
    >>> list(unique_everseen('ABBCcAD', str.lower))
    ['A', 'B', 'C', 'D']

    """
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in itertools.filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element 
Example 19
Project: pytorch-template   Author: lyakaap   File: losses.py    License: MIT License 6 votes vote down vote up
def mean(l, ignore_nan=True, empty=0):
    """
    nanmean compatible with generators.
    """
    l = iter(l)
    if ignore_nan:
        l = filterfalse(isnan, l)
    try:
        n = 1
        acc = next(l)
    except StopIteration:
        if empty == 'raise':
            raise ValueError('Empty mean')
        return empty
    for n, v in enumerate(l, 2):
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 20
Project: catalyst   Author: catalyst-team   File: lovasz.py    License: Apache License 2.0 6 votes vote down vote up
def mean(values, ignore_nan=False, empty=0):
    """
    Nanmean compatible with generators.
    """
    values = iter(values)
    if ignore_nan:
        values = ifilterfalse(isnan, values)
    try:
        n = 1
        acc = next(values)
    except StopIteration:
        if empty == "raise":
            raise ValueError("Empty mean")
        return empty
    for n, v in enumerate(values, 2):  # noqa: B007
        acc += v
    if n == 1:
        return acc
    return acc / n 
Example 21
Project: fiasko_bro   Author: devmanorg   File: repository_info.py    License: MIT License 5 votes vote down vote up
def get_parsed_py_files(self, whitelist=None):
        parsed_py_files = self._parsed_py_files
        if whitelist:
            parsed_py_files = filterfalse(
                lambda parsed_file: parsed_file.is_in_whitelist(whitelist),
                parsed_py_files
            )
        return parsed_py_files 
Example 22
Project: fiasko_bro   Author: devmanorg   File: ast_helpers.py    License: MIT License 5 votes vote down vote up
def get_assigned_names_excluding_class_attributes(tree):
    assigned_items = get_assigned_vars(tree, names_only=False)
    return {
        getattr(node, 'id', None) for node in filterfalse(is_class_attribute, assigned_items)
    } 
Example 23
Project: algo   Author: wangzheng0822   File: topological_sorting.py    License: Apache License 2.0 5 votes vote down vote up
def tsort_by_kahn(self) -> None:
        in_degree = [0] * self._num_vertices
        for v in range(self._num_vertices):
            if len(self._adjacency[v]):
                for neighbour in self._adjacency[v]:
                    in_degree[neighbour] += 1
        q = deque(filterfalse(lambda x: in_degree[x], range(self._num_vertices)))
        while q:
            v = q.popleft()
            print(f"{v} -> ", end="")
            for neighbour in self._adjacency[v]:
                in_degree[neighbour] -= 1
                if not in_degree[neighbour]:
                    q.append(neighbour)
        print("\b\b\b   ") 
Example 24
Project: open-synthesis   Author: twschiller   File: util.py    License: GNU General Public License v3.0 5 votes vote down vote up
def partition(pred, iterable):
    """Use a predicate to partition entries into false entries and true entries."""
    # https://stackoverflow.com/questions/8793772/how-to-split-a-sequence-according-to-a-predicate
    # NOTE: this might iterate over the collection twice
    # NOTE: need to use filter(s) here because we're lazily dealing with iterators
    it1, it2 = itertools.tee(iterable)
    return itertools.filterfalse(pred, it1), filter(pred, it2)  # pylint: disable=bad-builtin 
Example 25
Project: traces   Author: datascopeanalytics   File: decorators.py    License: MIT License 5 votes vote down vote up
def ignorant(func):
    @wraps(func)
    def wrapper(iterable, *args, **kwargs):
        filtered = filterfalse(_is_none, iterable)
        return func(filtered, *args, **kwargs)

    return wrapper 
Example 26
Project: VLC-Scheduler   Author: EugeneDae   File: utils.py    License: MIT License 5 votes vote down vote up
def zip_equally(*iterables):
    # ['A1'], ['B1', 'B2', 'B3'], ['C1', 'C2'] ->
    # -> 'A1', 'B1', 'C1', 'A1', 'B2', 'C2', 'A1', 'B3', 'C1'
    if len(iterables) == 0:
        return []
    
    longest_iterable_length = len(max(iterables, key=len))
    
    iterables = [
        islice(cycle(l), longest_iterable_length) for l
        in filterfalse(lambda i: len(i) == 0, iterables)
    ]
    
    return chain(*[i for i in zip(*iterables)]) 
Example 27
Project: resolwe   Author: genialis   File: process.py    License: Apache License 2.0 5 votes vote down vote up
def assertFile(self, obj, field_path, fn, **kwargs):
        """Compare a process's output file to the given correct file.

        :param obj: object that includes the file to compare
        :type obj: ~resolwe.flow.models.Data

        :param str field_path: path to
            :class:`~resolwe.flow.models.Data` object's field with the
            file name

        :param str fn: file name (and relative path) of the correct
            file to compare against. Path should be relative to the
            ``tests/files`` directory of a Django application.

        :param str compression: if not ``None``, files will be
            uncompressed with the appropriate compression library
            before comparison.
            Currently supported compression formats are *gzip* and
            *zip*.

        :param filter: function for filtering the contents of output
            files. It is used in :func:`itertools.filterfalse` function
            and takes one parameter, a line of the output file. If it
            returns ``True``, the line is excluded from comparison of
            the two files.
        :type filter: ~types.FunctionType

        :param bool sort: if set to ``True``, basic sort will be performed
            on file contents before computing hash value.

        """
        field = dict_dot(obj.output, field_path)
        self._assert_file(obj, field["file"], fn, **kwargs) 
Example 28
Project: resolwe   Author: genialis   File: process.py    License: Apache License 2.0 5 votes vote down vote up
def assertFiles(self, obj, field_path, fn_list, **kwargs):
        """Compare a process's output file to the given correct file.

        :param obj: object which includes the files to compare
        :type obj: ~resolwe.flow.models.Data

        :param str field_path: path to
            :class:`~resolwe.flow.models.Data` object's field with the
            list of file names

        :param list fn_list: list of file names (and relative paths) of
            files to compare against. Paths should be relative to the
            ``tests/files`` directory of a Django application.

        :param str compression: if not ``None``, files will be
            uncompressed with the appropriate compression library
            before comparison.
            Currently supported compression formats are *gzip* and
            *zip*.

        :param filter: Function for filtering the contents of output
            files. It is used in :obj:`itertools.filterfalse` function
            and takes one parameter, a line of the output file. If it
            returns ``True``, the line is excluded from comparison of
            the two files.
        :type filter: ~types.FunctionType

        :param bool sort: if set to ``True``, basic sort will be performed
            on file contents before computing hash value.

        """
        field = dict_dot(obj.output, field_path)

        if len(field) != len(fn_list):
            self.fail(
                msg="Lengths of list:basic:file field and files list are not equal."
            )

        for fn_tested, fn_correct in zip(field, fn_list):
            self._assert_file(obj, fn_tested["file"], fn_correct, **kwargs) 
Example 29
Project: Clean-Code-in-Python   Author: PacktPublishing   File: generators_pythonic_2.py    License: MIT License 5 votes vote down vote up
def partition(condition, iterable):
    """Return 2 new iterables

    true_cond, false_cond = partition(condition, iterable)

    * in true_cond, condition is true over all elements of iterable
    * in false_cond, condition is false over all elements of iterable
    """
    for_true, for_false = tee(iterable)
    return filter(condition, for_true), filterfalse(condition, for_false) 
Example 30
Project: Clean-code-in-Python   Author: rmariano   File: generators_pythonic_2.py    License: MIT License 5 votes vote down vote up
def partition(condition, iterable):
    """Return 2 new iterables

    true_cond, false_cond = partition(condition, iterable)

    * in true_cond, condition is true over all elements of iterable
    * in false_cond, condition is false over all elements of iterable
    """
    for_true, for_false = tee(iterable)
    return filter(condition, for_true), filterfalse(condition, for_false)