已知长度为n的字符串,获取所有可能的全排序 n!
def test(arr): length = len(arr) if length<=1: return arr res = [] for i in range(length): temp = list.copy(arr) del(temp[i]) res += [arr[i]+j for j in test(temp)] return res print(test([‘a‘,‘b‘,‘c‘,‘d‘]))
result:
G:\python\study>python hello.py
[‘abcd‘, ‘abdc‘, ‘acbd‘, ‘acdb‘, ‘adbc‘, ‘adcb‘, ‘bacd‘, ‘badc‘, ‘bcad‘, ‘bcda‘, ‘bdac‘, ‘bdca‘, ‘cabd‘, ‘cadb‘, ‘cbad‘, ‘cbda‘, ‘cdab‘, ‘cdba‘, ‘dabc‘, ‘dacb‘, ‘dbac‘, ‘dbca‘, ‘dcab‘, ‘dcba‘]
输出k个的排列组合,k不大于字符串长度 n!/(n-k)!
def test(arr,k): length = len(arr) if k<=1: return arr res = [] for i in range(length): temp = list.copy(arr) del(temp[i]) res += [arr[i]+j for j in test(temp,k-1)] return res print(test([‘a‘,‘b‘,‘c‘,‘d‘],2))
result:
G:\python\study>python hello.py
[‘ab‘, ‘ac‘, ‘ad‘, ‘ba‘, ‘bc‘, ‘bd‘, ‘ca‘, ‘cb‘, ‘cd‘, ‘da‘, ‘db‘, ‘dc‘]
时间: 2024-12-27 23:35:46