all permutations of a binary sequence x bits long

前端 未结 5 1168
陌清茗
陌清茗 2020-11-30 03:57

I would like to find a clean and clever way (in python) to find all permutations of strings of 1s and 0s x chars long. Ideally this would be fast and not require doing too m

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 04:50

    Kudos to all the clever solutions before me. Here is a low-level, get-you-hands-dirty way to do this:

    def dec2bin(n):
        if not n:
            return ''
        else:
            return dec2bin(n/2) + str(n%2)
    
    def pad(p, s):
        return "0"*(p-len(s))+s
    
    def combos(n):
        for i in range(2**n):
            print pad(n, dec2bin(i))
    

    That should do the trick

提交回复
热议问题