0

我希望它将一组数字作为输入,例如 [1,2,3,4],并且只给出具有奇数和的子集。例如,[1]、[1,2]、[2,3] 等。

我没有尝试太多,我不知道从哪里开始。抱歉,我对编程很陌生,但这是我到目前为止所拥有的。它生成所有可能的子集。

    def rsubsets(s):
        if len(s) == 0:
           return [[]]
        temp = rsubsets(s[1:])
        new = []
        for itm in temp:
           new.append(itm)
        n = len(new)
        for j in range(n):
           new[j] = new[j] + [s[0]]
        return temp + new

谢谢。

4

2 回答 2

3

建立在您现有的功能上:

def odd_subsets(s):
    return [x for x in rsubsets(s) if sum(s) % 2 == 1]

或者没有理解:

def odd_subsets(s):
    odd = []
    for subset in rsubsets(s):
        if sum(s) % 2 == 1:
            odd.append(subset)
    return odd
于 2012-12-02T22:11:51.417 回答
1
def odd_subsets(s):
    lRet = []
    for i in range(len(s)):
        lRet.extend([c for c in itertools.combinations(s,i+1) if sum(c)%2==1])
    return lRet

如果您对使用初始功能一无所知,这是最简单的方法

def rsubsets(s):
    def all_subsets(s):
        if len(s) == 0:
           return [[]]
        temp = all_subsets(s[1:])
        new = []
        for itm in temp:
           new.append(itm)
        n = len(new)
        for j in range(n):
           new[j] = new[j] + [s[0]]
        return temp + new
    return [i for i in all_subsets(s) if sum(i)%2==1]

这几乎是调用您的初始递归函数并过滤结果。

另一种方法是使用标志...

def rsubsets(s,bFilter=True):
    if len(s) == 0:
        return [[]]
    temp = rsubsets(s[1:],False)
    new = []
    for itm in temp:
       new.append(itm)
    n = len(new)
    for j in range(n):
       new[j] = new[j] + [s[0]]
    if bFilter:
        return [i for i in temp+new if sum(i)%2 ==1]
    return temp + new
于 2012-12-02T22:10:47.080 回答