遍历所有二进制组合,其中一些数字为“?". [英] Going through all binary combinations with some numbers as "?"

查看:85
本文介绍了遍历所有二进制组合,其中一些数字为“?".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须生成给定字符串的所有可能的二进制表示形式,其中某些字符是?"其他为1或0.

I have to generate all the possible binary representations of a given string, where some characters are "?" and others are 1 or 0.

我正在尝试进行递归搜索,但是遇到了一些我无法弄清的怪异问题.

I'm trying to do a recursive search but I encounter some weird problems I can't figure out.

userInput = list(input())
anslist = []
def fill(inp):
    #print(inp)
    if inp.count("?") == 0:
        print(inp, "WAS ADDED")
        anslist.append(inp)
        return


    for a in range(0, len(userInput)):
        if inp[a] == "?":
            inp[a] = 1
            fill(inp)
            inp[a] = 0
            fill(inp)
            return
print(anslist)   

对于输入?01?1,我应该得到: 00101、00111、10101和10111 但是我明白了 10111 10101 00101已打印出来.此外,anslist无法正常运行.我似乎无法弄清楚这一点.

For the input ?01?1 I should be getting: 00101, 00111, 10101 and 10111 but I get 10111 10101 00101 printed out. In addition, anslist isn't working properly. I just can't seem to figure this out.

推荐答案

a list mutable 类型,这意味着您只有一个列表,可以在列表上进行所有修改.这将导致您的第一个呼叫fill(inp)也填充剩余的?"在inp中,因此只有第一个选项的第二个选项会给您一个结果(第一个?= 1:两个结果,第一个?= 0:一个结果,因为第一个?的最后一个结果仍保存在列表中)

a list is a mutable type, that means that you only have one list on which all modifications are made. This causes your first call fill(inp) to also fill the remaining '?' in inp, thus only giving you one result with the second option for the first ? (first ?=1: two results, first ?=0: one result because the last result of the first ? is still saved in the list)

要解决此问题,请使用list.copy().这会将列表的副本传递给fill(),从而使原始列表保持原样.

To resolve this problem, use list.copy(). This will pass a copy of the list to fill() and thus cause the original list to be left as it is.

具有.copy()和其他较小修改的完整代码:

Your complete code with .copy() and other minor modifications:

anslist = []
def fill(inp):
    if inp.count("?") == 0:
        print(inp, "WAS ADDED")
        anslist.append(inp)
        return

    for a in range(len(inp)):  # range(0, x) is equivalent to range(x); try to limit global variables
        if inp[a] == "?":
            inp[a] = 1
            fill(inp.copy())  # list is mutable
            inp[a] = 0
            fill(inp.copy())  # see above
            return
user_input = list(input())
fill(user_input)
print(anslist)

这篇关于遍历所有二进制组合,其中一些数字为“?".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆