[Python] Efficiently count lists with certain properties

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    My purpose is to count permutations with certain properties. I first generate the permutations and then remove those that do not satisfy the desired properties. How could I improve the code to be able to enumerate more permutations?

    from itertools import permutations

    def check(seq, verbose=False):
    """check that the elements of the sequence equal a difference of previous elements"""
    n = len(seq)
    for k in range(1, n-1):
    # build a set of admissible values
    dk = {abs(seq-seq[j]) for i in range(0, k) for j in range(i+1, k+1) if i < j}
    if k > 0 and verbose:
    print('current index = ', k)
    print('current subsequence = ', seq[:k+1])
    print('current admissible values = ', dk)
    print('next element = ', seq[k+1])
    # check if the next element is in the set of admissible values
    if k > 0 and seq[k+1] not in dk:
    # return an invalid subsequence (k+2 to include the invalid element)
    return seq[:k+2]
    return seq

    def is_valid(seq):
    """check that the sequence satisfies certain properties"""
    n = len(seq)
    if n < 3:
    return False
    if len(check(seq)) == n:
    return True
    return False

    def filter_perms(perms):
    for perm in perms:
    if is_valid(perm): yield perm

    def make_perms(n):
    """The elements of the list are integers, where a list of length n stores all integers from 1 to n."""
    for p in permutations(range(1,n-1)):
    yield (n,) + p + (n-1,)

    def enumerate_perms(n):
    perms = make_perms(n)
    return filter_perms(perms)

    # testing a good sequence
    seq=(5, 2, 3, 1, 4)
    check(seq, verbose=True)
    is_valid(seq)
    # True

    # testing a bad sequence
    seq=[5, 2, 1, 3, 4]
    check(seq, verbose=True)
    is_valid(seq)
    # False

    # testing permutations
    tuple(make_perms(5))

    # testing enumeration
    tuple(enumerate_perms(5))
    # ((5, 2, 3, 1, 4), (5, 3, 2, 1, 4))

    len(tuple(enumerate_perms(14)))
    # 29340


    Summary of discussions in the comments section: Should I use numpy arrays? Should I save the permutations to a database?

    Continue reading...

Compartilhe esta Página