Python 为什么它返回的时间值与其递归函数调用的时间值相同?

Python 为什么它返回的时间值与其递归函数调用的时间值相同?,python,python-3.x,recursion,itertools,Python,Python 3.x,Recursion,Itertools,在这个程序中,我创建了所有可能集合的子集,然后我对每个集合进行位运算('OR','|'),然后添加它们,取模并打印答案 例如: n=3(Size of array or list) b= 2 5 5 所有可能的设置: [[2,5],[2,5],[5,5],[2,5,5]] [2,5]=7, [2,5]=7, [5,5]=5, [2,5,5]=7 添加所有这些:7+7+5+7=26 import itertools def subs(l): res=[] for i in r

在这个程序中,我创建了所有可能集合的子集,然后我对每个集合进行位运算('OR','|'),然后添加它们,取模并打印答案

例如:

n=3(Size of array or list)
b= 2 5 5
所有可能的设置:

[[2,5],[2,5],[5,5],[2,5,5]]
[2,5]=7, [2,5]=7, [5,5]=5, [2,5,5]=7
添加所有这些:
7+7+5+7=26

import itertools

def subs(l):
    res=[]
    for i in range(2,len(l)+1):
        for combo in itertools.combinations(l,i):
            res.append(list(combo))
    return res

def bitwise_operation(c):
#print("List of c : ",c)
if(len(c)>1):
        bitwise=c[0]|c[1]
        #print("Before del C : ",c)
        del c[0:2]
        #print("After  del C : ",c)
        c.append(bitwise)
        #print("After append C : ",c)
        if(len(c)>1):
            bitwise_operation(c)
print(c[0])
return c[0]

n=int(input())
bit=[]
a=list(map(int,input().split()))
b=[]
if len(a)!=n:
    exit()
else:
b=subs(a)
#print(b)
for j in range(len(b)):
    for k in range(len(b[j])-1):
        if len(b[j])>1:
            bitwise=bitwise_operation(b[j])
        #print(bitwise)
        bit.append(bitwise)
prev_ans=sum(bit)
ans=prev_ans%1000000007
print(ans)
问题是,当我使用递归
函数(按位_操作)[2,5,5]=[2,5]->7[7,5]->7………
进行按位操作时,其返回值为
[2,5,5]=7

它在同一集中返回两次
7,7


我如何解决这个问题?

您的问题就在这里。将
b[3]
(元素
[2,5,5]
)的结果追加两次

这是一个非常复杂的方法来做一件简单的事情。我会重新给你贴标签,弄清楚你在干什么

for index in range(len(b)):
    element = b[index]
    for times in range(len(element)-1):  # do this one time for element of len(2) and two times for an element of len(3) 
        if len(element)>1:
            bitwise=bitwise_operation(element)  # change the value of bitwise and mutate the element
        #print(bitwise)
        bit.append(bitwise)  # append that value whether it changed or not.
因此,当您运行外部循环时,它会将[2,5,5]的值附加两次,给您额外的7

通过直接迭代
b
可以得到正确的结果

for element in b:
    bit.append(bitwise_operation(element))
这应该会给你正确的答案

另一方面,
按位_操作
可以通过直接在列表上迭代而大大简化

def new_bitwise_operation(lst):
    answer = 0
    for element in lst:
        answer = answer | element
    return answer

bitwise_操作的缩进是否正确?
c.append(bitwise)
-您是否打算将按位结果添加到末尾?是否为
7.5
按位_操作的
bitwise_操作的预期输出为
[[2,5],[2,5],[5,5]]
?不清楚您的问题是什么或您的预期结果是什么-当我执行
按位_操作([2,5,5])
时,它只返回
7
。最后,您的递归函数可以替换为
functools.reduce(operator.or,c)
def new_bitwise_operation(lst):
    answer = 0
    for element in lst:
        answer = answer | element
    return answer