Python Forum
A combinations instance with random access
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A combinations instance with random access
#1
Instances of this class Combinations are slow replacements for itertools.combinations() if they are iterated. On the other hand, they have the Sequence interface, meaning a length and random access. For example one can ask the 2**85 th item of Combinations(range(1_000_000), 9) without iterating the instance.

MIT License added so that you can freely use it and modify it.

"""
MIT License

Copyright (c) 2022 User Gribouillis at www.python-forum.io

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
__doc__ = ""
import collections.abc
from scipy.special import comb

__version__ = '2022.11.11'

class Combinations(collections.abc.Sequence):
    """Slow version of itertools.combinations with indexed access

    Instances implement the Sequence interface of collections.abc
    """
    def __init__(self, seq, k):
        """Initialises the Combinations instance.

        Arguments:
            seq : a sequence implementing indexed access
            k a number in range(len(seq))
        """
        self.seq = seq
        self.n = len(seq)
        self.k = k
        self.co = comb(self.n, k, exact=True)

    def __len__(self):
        return self.co

    def _gen_item(self, idx):
        n, k, co = self.n, self.k, self.co
        if not (0 <= idx < co):
            raise IndexError(f'argument out of range({co}), got {idx}')
        i = -1
        while 0 < k <= n:
            i += 1
            c = k * co / n # k-1 among n-1
            if idx >= c:
                idx -= c
                co = (n - k) * co / n # k among n-1
            else:
                k -= 1
                co = c
                yield i
            n -= 1

    def __getitem__(self, idx):
        s =  self.seq
        return tuple(s[i] for i in self._gen_item(idx))

    def __iter__(self):
        for i in range(len(self)):
            yield self[i]

    def __reversed__(self):
        for i in range(len(self)-1, -1, -1):
            yield self[i]

def main():
    w = Combinations(range(6), 3)
    for i in range(len(w)):
        print(w[i])
    print('-' * 30)
    for t in reversed(w):
        print(t)

if __name__ == '__main__':
    main()
Output:
(0, 1, 2) (0, 1, 3) (0, 1, 4) (0, 1, 5) (0, 2, 3) (0, 2, 4) (0, 2, 5) (0, 3, 4) (0, 3, 5) (0, 4, 5) (1, 2, 3) (1, 2, 4) (1, 2, 5) (1, 3, 4) (1, 3, 5) (1, 4, 5) (2, 3, 4) (2, 3, 5) (2, 4, 5) (3, 4, 5) ------------------------------ (3, 4, 5) (2, 4, 5) (2, 3, 5) (2, 3, 4) (1, 4, 5) (1, 3, 5) (1, 3, 4) (1, 2, 5) (1, 2, 4) (1, 2, 3) (0, 4, 5) (0, 3, 5) (0, 3, 4) (0, 2, 5) (0, 2, 4) (0, 2, 3) (0, 1, 5) (0, 1, 4) (0, 1, 3) (0, 1, 2)
Larz60+ likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020