[Python] Need to enumerate all combinations of n items being assigned one of two values

Discussão em 'Python' iniciado por Stack, Julho 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have been working on this problem as a subsection of a project, so it is possible I am missing something obvious, so please forgive me if that is the case. (Working in Python)

    Currently I have a function that is enumerating every combination of elements of the numbers 1-24, choosing between 1-12 elements. That is, it produces the numbers 1-24, then all combinations of two numbers between 1-24, then all combinations of three numbers between 1-24, and so on up to all combinations of twelve numbers between 1-24.

    For each value of n (where 1<n<12, as n is the number of numbers between 1-24 being used at a given time), I want to look at the set of n items and consider all combinations of those being assigned one of two values (I am using positive and negative). So for n=1, I need to look at 1 and -1, then 2 and -2... 24 and -24. When n=2, I want to look at 1 and 2, 1 and -2, -1 and 2, and -1 and -2, then 1 and 3, 1 and -3, -1 and 3, and -1 and -3, and so on up to 23 and 24. Then I would repeat this with three elements in the range 1-24, then four... up to twelve.

    It may be worth noting that I am applying this pattern to a specific context, and likely will not actually need up to twelve, that is simply a maximum value that I know satisfies my problem. Given that I am able to enumerate the sets of elements I need, what would be a clean and efficient way to apply the positive and negative values?

    Continue reading...

Compartilhe esta Página