Python 通过从两个列表中删除第一个元素并附加到新列表来查找每个可能的列表
我有两个整数列表,a和b,它们的长度不一定相同。我希望通过删除a的第一个元素或b的第一个元素,并将其附加到新列表中,重复此步骤,直到a和b都为空,从而从这些列表中创建新列表。在这个过程中的每一步,可能列表的数量都呈指数增长,我想知道如何生成以这种方式创建的每个列表 到目前为止,我只设法计算出可能列表的数量等于Python 通过从两个列表中删除第一个元素并附加到新列表来查找每个可能的列表,python,permutation,Python,Permutation,我有两个整数列表,a和b,它们的长度不一定相同。我希望通过删除a的第一个元素或b的第一个元素,并将其附加到新列表中,重复此步骤,直到a和b都为空,从而从这些列表中创建新列表。在这个过程中的每一步,可能列表的数量都呈指数增长,我想知道如何生成以这种方式创建的每个列表 到目前为止,我只设法计算出可能列表的数量等于sum((2**I代表范围内的I(len(a)+len(b)))。我不知道如何进行这项工作,如果有任何指点,我将不胜感激 作为参考,我的最终目标是计算出每个列表中连续元素之间差异的总和,并找
sum((2**I代表范围内的I(len(a)+len(b)))
。我不知道如何进行这项工作,如果有任何指点,我将不胜感激
作为参考,我的最终目标是计算出每个列表中连续元素之间差异的总和,并找出其中的最小值。我认为这可以通过使用递归来实现。一些代码
permutation = [0]*10 # size of this list has to be equal to lenth of list1 + length of list2. (you can have 4 as the size of the list).
def task(list1,list2,index):
if len(list1)==0 and len(list2)==0: # if length of both the list is 0, we print the
print(permutation) # permutation list
return
if len(list1)>0:
permutation[index] = list1[0]
modified_list1 = list1[:] # Since lists in python are passed by reference, I am making a copy of the list
modified_list1.pop(0) # Removing the first element
task(modified_list1,list2,index+1) #and calling the function again using the modified list.
if len(list2)>0:
permutation[index] = list2[0]
modified_list2 = list2[:]
modified_list2.pop(0)
task(list1,modified_list2,index+1)
if __name__=="__main__":
list1 = [1]
list2 = [4,5,6]
task(list1,list2,0)
递归解决方案可能有点难理解,我鼓励你
要复制一个副本和一支笔,并尝试模拟它的小输入,您将
了解事情是如何运作的
对于您的下一个任务,当我们打印排列列表时,您可以计算相邻数字的差异,并以任何方式存储结果。
itertools.permutations(a+b)
?这正是我想要的,谢谢。通过在task()
中定义permutation
,可以使函数更加独立,但我还没有弄明白这一点,而且它也不是至关重要的。