It is necessary to obtain all possible combinations of the arrangement + and - for a given length, for example, for 2 it will be ++, -, + -, - +.

    3 answers 3

    itertools.cobinations() does an excellent job with this task.

    In order not to lose the mirror combinations '+-', '-+' pass the double string '+-+-' , and in order for the combinations not to repeat, use set() .

     from itertools import combinations print(set(combinations('+-'*2, 2))) 
    • Thank you, I understood correctly to get combinations for three characters - does the string also need triple, for 4 quadruple, etc.? - Sergey
    • @Sergey yes, for N, it looks like this: print(set(combinations('+-'*n, n))) - pinguin

    If +- and -+ are different in your case, then you do not need combinations ( combinations ) (which do not take the order into account), but itertools.product() ( placement with repetitions ):

     >>> import itertools >>> print(*map(''.join, itertools.combinations('+-', r=2))) +- >>> print(*map(''.join, itertools.combinations_with_replacement('+-', r=2))) ++ +- -- >>> print(*map(''.join, itertools.product('+-', repeat=2))) ++ +- -+ -- 

      Note that each such arrangement corresponds to a binary record of a certain number, only - instead of 0 is written - , and instead of one - plus.

      Hence the simple method of generation is to list in the cycle all the numbers from 0 to 2^N-1 , displaying their binary representation using the alphabet "-+"

        N = 4 for k in range(1<<N): print(''.join('+' if (1 & (k >> i)) else '-' for i in range(N))) 

      If the lines flip [::-1] , the order will be lexicographical

      • for n in range(2**N): print(f'{n:0{N}b}'.translate(dict(zip(map(ord, "10"), "+-")))) jfs
      • @jfs f'{n:0{N}b}' how to interpret? - MBo
      • f-string : format n in binary, complementing up to N digits from the left with zeros if necessary. - jfs
      • @jfs Oh, thanks. IMHO, it is still difficult to read without experience. - MBo
      • from the complex here, that {N} nested inside {n} . And since the language for str.format is useful to know if you are programming on Python. - jfs