Python / Functional noob,将不可读的Java递归转换为Python

时间:2015-04-09 08:56:18

标签: java python recursion functional-programming

我正试图粉碎一些核心编码技能,但大脑因为过多的Java而中毒:(。我从递归开始,这是一段简单的代码。

static ArrayList<String> createSentences(ArrayList<String[]> listsOfWords, int listIdx) {
    if (listIdx == listsOfWords.size())
        return null;

    String[] currListOfWords = listsOfWords.get(listIdx);
    ArrayList<String> sentences = new ArrayList<>();
    for (String word : currListOfWords) {
        ArrayList<String> fragments = createSentences(listsOfWords, listIdx + 1);
        if (fragments != null) {
            for (String fragment : fragments) {
                sentences.add(word + " " + fragment);
            }
        } else {
            sentences.add(word);
        }
    }

    return sentences;
}

此代码正在执行的是以表单形式输入...

{
 {"tom","dick","harry"},
 {"was","is"}
 {"noob","average","expert"}
}

并将其转换为以下内容......

"tom was noob"
"tom was average"
"tom was expert"
"dick was noob"
"dick was average"
"dick was expert"

......等等

这只是f(n + 1)= L(n)+ f(n)形式的递归?

我的猜测是有更好的方法用Python(或其他功能语言)来表示它

任何人都可以指出我正确的方向

  1. 使用Python可以使这些代码更具可读性吗?我的眼睛流血了 看看上面的代码示例。
  2. 练习递归时我应该考虑另一种语言吗?哈斯凯尔可能吗?
  3. 此致

1 个答案:

答案 0 :(得分:2)

python中最简单的方法是使用itertools.product

print("\n".join(" ".join(tup) for tup in itertools.product(*l)))

要递归地执行此操作,您可以使用列表解析:

def rec_prod(l):
    if not l:
        return [[]]
    else:
        return [[name] + prod for name in l[0] for prod in rec_prod(l[1:])]
print("\n".join(" ".join(tup) for tup in rec_prod(l)))


tom was noob 
tom was average 
tom was expert 
tom is noob 
tom is average 
tom is expert 
dick was noob 
dick was average 
dick was expert 
dick is noob 
dick is average 
dick is expert 
harry was noob 
harry was average 
harry was expert 
harry is noob 
harry is average 
harry is expert 

这相当于嵌套for循环:

for name in l[0]:
    for i in l[1]:
        for w in l[2:]:
            print(name,i,w)