二进制字符串递归函数

时间:2019-04-06 17:52:16

标签: python binary

如何编写一个递归函数来生成长度为n的二进制列表(指定数目为1s)? 这是一个递归生成二进制列表的代码;没有指定的1的数量:

def generateAllBinaryStrings(n, arr, i):  

    if i == n: 
        printTheArray(arr, n)  
        return

    # First assign "0" at ith position  
    # and try for all other permutations  
    # for remaining positions  
    arr[i] = 0
    generateAllBinaryStrings(n, arr, i + 1)  

    # And then assign "1" at ith position  
    # and try for all other permutations  
    # for remaining positions  
    arr[i] = 1
    generateAllBinaryStrings(n, arr, i + 1)  

来自geeksforgeeks

2 个答案:

答案 0 :(得分:0)

您可以这样做:

def binaryStrings(n, ones):  
    if n < ones: # impossible
        return []
    if n == ones:
        return ["1" * ones]
    if ones == 0:
        return ["0" * n]
    a = binaryStrings(n-1, ones)
    b = binaryStrings(n-1, ones-1)
    return ["0"+s for s in a] + ["1"+s for s in b]

示例调用以获取所有正好具有4个1位数字的所有6位二进制数:

print(binaryStrings(6,4))

答案 1 :(得分:0)

必须生成所有可能的序列,并在每个位置添加0或1。总可能的序列= 2 ^ MAX。跟踪当前序列中迄今为止要中断的1s。

# Generate all binary numbers with exactly "n" 1s
# Max digits in the binary number = MAX

def binary(n):
    MAX = 5
    all_solutions = []
    def solve(current, remaining_ones):
        if len(current) > MAX:
            return
        if remaining_ones == 0:
            all_solutions.append(current+"0"*(MAX-len(current)))
            return

        solve(current+"1", remaining_ones - 1)
        solve(current+"0", remaining_ones)

    solve("", n)
    return all_solutions

 print(binary(2))
 # ['11000', '10100', '10010', '10001', '01100', '01010', '01001', '00110', '00101', '00011']