通过从两个列表中的任何一个中删除第一个元素并附加到新列表来查找每个可能的列表
Finding every possible list made by removing the first element from either of two lists and appending to the new list
我有两个整数列表,a 和 b,它们的长度不一定相同。我想通过删除 a 的第一个元素或 b 的第一个元素并将其附加到新列表来从这些列表中创建新列表,重复此步骤直到 a 和 b 都为空。在此过程中的每一步,可能列表的数量都会呈指数增长,我想知道如何生成每个可能以这种方式创建的列表。
到目前为止,我只设法计算出可能列表的数量等于 sum((2**i for i in range(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)
递归解决方案可能有点难以理解,我会鼓励你
拿一份复印件和笔并尝试模拟它进行少量输入,你会
了解事情是如何运作的。
对于你的下一个任务,当我们打印排列列表时,你可以计算相邻数字的差异并以你想要的任何方式存储你的结果。
我有两个整数列表,a 和 b,它们的长度不一定相同。我想通过删除 a 的第一个元素或 b 的第一个元素并将其附加到新列表来从这些列表中创建新列表,重复此步骤直到 a 和 b 都为空。在此过程中的每一步,可能列表的数量都会呈指数增长,我想知道如何生成每个可能以这种方式创建的列表。
到目前为止,我只设法计算出可能列表的数量等于 sum((2**i for i in range(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)
递归解决方案可能有点难以理解,我会鼓励你 拿一份复印件和笔并尝试模拟它进行少量输入,你会 了解事情是如何运作的。
对于你的下一个任务,当我们打印排列列表时,你可以计算相邻数字的差异并以你想要的任何方式存储你的结果。