python - 从可以是 A、B 或 C 的 n 个字符中生成所有单词的函数
问题描述
我们需要创建一个函数,将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,密件抄送、抄送
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))
解决方案
使用递归解决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));
}
}
推荐阅读
- arrays - 如果项目与字符串数组匹配,则从 Ruby 哈希数组中删除项目
- r - 无法使用 R 中的 download.file 下载网页
- multithreading - 无法将 Worker-Loader 与 Vuejs 和 Webpack 一起使用
- javascript - 强制定义一个可选的接口属性
- android - Android startForeground 在活动关闭后重新启动
- java - Drools - 规则数量和永久空间之间是否存在直接关联?
- javascript - 如何在threejs/tween.js中让对象一步一步移动
- python-3.x - 将值从另一列数据框更新到另一个数据框
- javascript - Javascript - 邮件
- python - mutliindex dask 数据帧到 2d dask 数组