如何合并两个列表以找到最小的重复因子?

时间:2019-04-28 06:18:48

标签: python algorithm dynamic-programming

例如,我有两个列表

A = ["spin", "dab", "dab", "moonwalk", "clap", "moonwalk"]
B = ["dab", "dab", "spin", "clap", "clap", "moonwalk"]

合并两个列表后,我可能会有一个这样的列表

remix=["dab", "spin", "dab", "spin", "dab", "clap", "dab", "moonwalk", "clap", "moonwalk", "clap", "moonwalk"]

我的问题是如何合并两个列表,以使元素的相邻重复最小(A和B中的所有元素必须出现在混音列表中)。 重复是这样的

remix=["spin", "dab", "spin", "dab", "dab", "clap", "dab", "moonwalk", "clap", "moonwalk", "clap", "moonwalk"]

这里的相邻重复是2 * dab

另一个示例是

remix=["spin", "dab", "spin", "dab", "dab", "clap", "clap","dab", "moonwalk", "moonwalk", "clap", "moonwalk"]

相邻的重复是2 * dab + 2 * clap

以下是此问题的输入

A = ["spin", "dab", "dab", "moonwalk", "clap", "moonwalk"]
B = ["dab", "dab", "spin", "clap", "clap", "moonwalk"]
factor={"spin":1,"dab":2,"moonwalk":3,"clap":4}

输出列表:

["dab", "spin", "dab", "spin", "dab", "clap", "dab", "moonwalk", "clap", "moonwalk", "clap", "moonwalk"]

原因是没有重复,因此任何元素的相邻重复均为0。 同样,我们的目标是找到具有最小相邻重复的列表,如果我们可以找到一个完全没有重复的列表,则因子当然可以为0

我当时在考虑动态编程,但是我不知道如何使它起作用。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

我不太确定您的预期输出。你的意思是这样吗?

import random
A = ["spin", "dab", "dab", "moonwalk", "clap", "moonwalk"]
B = ["dab", "dab", "spin", "clap", "clap", "moonwalk"]

AB = A + B
elem = AB
while elem != []:
    random.shuffle(AB)
    elem = []
    for i in range(len(AB)-1):
        if AB[i] == AB[i+1]:
            elem.append([AB[i],AB[i+1]])
    print (AB)
    print (elem)
    print ("Repetition factor: ")
    for e in elem:
        print(str(len(e)) + "*" + e[0])
    print ("\n")

输出:

['spin', 'moonwalk', 'dab', 'dab', 'spin', 'dab', 'moonwalk', 'moonwalk', 'clap', 'clap', 'dab', 'clap']
[['dab', 'dab'], ['moonwalk', 'moonwalk'], ['clap', 'clap']]
Repetition factor: 
2*dab
2*moonwalk
2*clap

['spin', 'dab', 'clap', 'dab', 'moonwalk', 'dab', 'dab', 'clap', 'moonwalk', 'clap', 'moonwalk', 'spin']
[['dab', 'dab']]
Repetition factor: 
2*dab

['moonwalk', 'dab', 'clap', 'moonwalk', 'clap', 'dab', 'spin', 'dab', 'moonwalk', 'clap', 'dab', 'spin']
[]
Repetition factor: