How do I compute all possibilities for an array of numbers/bits (in python, or any language for that matter)

前端 未结 4 1649
野趣味
野趣味 2020-12-04 01:53

I have been wracking my brains out for 3 hours straight, but I still don\'t get it, so I am asking here. (I wrote Python in the title, but this could be for pretty much any

4条回答
  •  囚心锁ツ
    2020-12-04 02:09

    import numpy as np
    def all_combinations(width, vals):
        return np.array(np.meshgrid(*[vals]*width,
                        indexing='ij')).reshape((width,-1)).transpose()
    
    print(all_combinations(width=3, vals=[0,1]))
    print(all_combinations(width=2, vals=['a','b','c']))
    

    Output:

    [[0 0 0]
     [0 0 1]
     [0 1 0]
     [0 1 1]
     [1 0 0]
     [1 0 1]
     [1 1 0]
     [1 1 1]]
    [['a' 'a']
     ['a' 'b']
     ['a' 'c']
     ['b' 'a']
     ['b' 'b']
     ['b' 'c']
     ['c' 'a']
     ['c' 'b']
     ['c' 'c']]
    

提交回复
热议问题