虽然网上有很多关于递归的信息,但我还没有找到任何可以应用于我的问题的信息。我对编程还是很陌生,所以如果我的问题很微不足道,请原谅。
感谢您的帮助:)
这就是我想要的结果:
listVariations(listOfItems, numberOfDigits)
>>> listVariations(['a', 'b', 'c'], 1)
>>> ['a', 'b', 'c']
>>> listVariations(['a', 'b', 'c'], 2)
>>> ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
>>> listVariations(['a', 'b', 'c'], 3)
>>> ['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']
但到目前为止,我只能想出一个需要提前指定/知道位数的函数。这是丑陋和错误的:
list = ['a', 'b', 'c']
def listVariations1(list):
variations = []
for i in list:
variations.append(i)
return variations
def listVariations2(list):
variations = []
for i in list:
for j in list:
variations.append(i+j)
return variations
def listVariations3(list):
variations = []
for i in list:
for j in list:
for k in list:
variations.append(i+j+k)
return variations
oneDigitList = listVariations1(list)
twoDigitList = listVariations2(list)
threeDigitList = listVariations3(list)
这可能非常简单,但我想不出一个在函数调用自身时连接字符串的好方法。
感谢您的努力:)
Tôi là một lập trình viên xuất sắc, rất giỏi!