Strony

niedziela, 21 lutego 2021

 Handy itertools:


  • powerset
    import itertols as it
    def powerset(iterable):
    """
    powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
    """
    s = list(iterable)
    return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1))
    view raw powerset hosted with ❤ by GitHub
  • all sublist from list
    def sublists(iterable):
    """ generate all of the sublist from *iterable*.
    >>> [s for s in sublists('hi')]
    [('h',), ('i',), ('h', 'i')]
    >>> list(sublists([0, 1, 2]))
    [(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)]
    """
    # The length-1 sublist
    seq = []
    for item in iter(iterable):
    seq.append(item)
    yield (item,)
    seq = tuple(seq)
    item_count = len(seq)
    # And the rest
    for n in range(2, item_count + 1):
    for i in range(item_count - n + 1):
    yield seq[i : i + n]
    view raw sublists hosted with ❤ by GitHub

Brak komentarzy:

Prześlij komentarz