[英]I can solve this with a loop but why hasn't all the combinations of the array displayed with this recursion function?
The code prints out all the combinations except for index [0:4:3] and I don't understand why.该代码打印出除索引 [0:4:3] 之外的所有组合,我不明白为什么。 I want to solve it using only recursion.
我想只使用递归来解决它。 So i am wondering why it skipping that one index.
所以我想知道为什么它会跳过那个索引。 If someone can explain that would help
如果有人可以解释那会有所帮助
combination=[] #create array
re=[3,34,2,1] #list to find all combinations
#name of function
def all_combinations(arr,x,y,z):
# if less than length of array for x let it pass
if x < len(arr)+1:
# if less than length of array for y let it pass
if y < len(arr)+1:
# if less than length of array for z let it pass
if z < (len(arr)+2):
if arr[x:y:z] not in combination:
combination.append(arr[x:y:z]) #add to array
z +=1 #increase z
all_combinations(arr,x,y,z) #recurse
y += 1 #increase y
z=1 #reset index
all_combinations(arr,x,y,z) #recurse
x += 1 #next x
y =0 #reset y
z=1 #reset z
all_combinations(arr,x,y,z) #recurse
all_combinations(re,0,1,1) #call function
print(combination) #print result
You reset of y places it at zero (instead of x+1).您重置 y 将其置于零(而不是 x+1)。 This will generate an empty combination arr[x:0:1] which will be present in the combinations the second time, thus breaking the recursion for all starting values of x after reaching the maximum end value for a given step size.
这将生成一个空组合 arr[x:0:1] ,该组合将第二次出现在组合中,从而在达到给定步长的最大结束值后中断 x 的所有起始值的递归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.