我需求是遇到這一個題目:
請將以下【歌曲】已發行日期由「新到舊」依序排列 【H】 After LIKE 【2】 I AM 【R】 ELEVEN 【7】LOVE DIVE 請以半形輸入法輸入正確答案之"選項",大小寫/阿拉伯數字需要一模一樣,範例:A4X8
要組合出這4個字母可以產生的 24種變化. (4x3x2x1)
服用下列的副程式, 就完成我的組合需求:
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(range(n, n-r, -1))
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
比較3種常用寫法:
https://docs.python.org/3/library/itertools.html
- combinations(‘ABCD’, 2) –> AB AC AD BC BD CD
- combinations_with_replacement(‘ABC’, 2) –> AA AB AC BB BC CC
- permutations(‘ABCD’, 2) –> AB AC AD BA BC BD CA CB CD DA DB D