【问题标题】:Function that generates all words out of n characters that can be A,B or C从可以是 A、B 或 C 的 n 个字符中生成所有单词的函数
【发布时间】:2020-05-05 18:29:34
【问题描述】:

我们需要创建一个函数,使 A、B 和 C 的所有组合具有 n。我尝试制作一些东西,我只让它适用于 0、1 和 2,但我不知道如何使用递归或嵌套循环来制作它。

n=3 的示例:

AAA,BAA,CAA,ABA,BBA,CBA,ACA,BCA,CCA,AAB,BAB,CAB,ABB,BBB,CBB,ACB,BCB,CCB,AAC,BAC,CAC,ABC,BBC,CBC , ACC, BCC, CCC


def generator (n):

    complete = [ ]

    words = ["A", "B", "C",]

    if (n==1):
        for word1 in words:
            complete.append(word1)
        return complete

    elif (n==0):
        return complete

    else:
        for word1 in words:
            for word2 in words:
                complete.append(word1+word2)

    return complete



n = int(input("Lenght n: "))

complete = (generator(n))

print(', '.join(complete))

【问题讨论】:

标签: python recursion


【解决方案1】:

使用递归解决java中的问题:

public static void main(String[] args) {
  String str = String.valueOf(words);
  printCombinations(str);
}

private static void printCombinations(String str) {
  printPermutation(str, "");
}

private static void printPermutation(String str, String str2) {
  if (str2.length() == str.length()) {
    //   printing the combination
    System.out.println(str2);
    return;
  }
  for (int i = 0; i < str.length(); i++) {
    printPermutation(str, str2 + str.charAt(i));
  }
}

【讨论】:

    【解决方案2】:

    问题在于递归逻辑,您需要以某种方式更改它以正确呈现递归逻辑,下面是一个示例:

        ...
        #produce results for n-1 length so we can use it later
        res=generator(n-1)
        for word1 in words:
                # for each partial result (length n-1) we can generate final result by concatenating current word to it
                for r1 in res:
                    complete.append(word1+r1)
    

    完整代码:

    def generator (n):
    
        complete = [ ]
    
        words = ["A", "B", "C",]
    
        if (n==1):
            for word1 in words:
                complete.append(word1)
            return complete
    
        elif (n==0):
            return complete
    
        else:
            res=generator(n-1)
            for word1 in words:
                    for r1 in res:
                        complete.append(word1+r1)
    
        return complete
    

    n=3 的结果:(27 个字符串)

    ['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA', 'CBB', 'CBC', 'CCA', 'CCB', 'CCC']
    

    【讨论】:

      猜你喜欢
      • 2012-03-03
      • 2022-10-13
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多