itertoolsモジュールではpermutations,combinations,productの使用
1725 ワード
from itertools import permutations,combinations,product
# , , , ,
strs = 'abc'
# 1
def zuHe(strs):
n = len(strs)
if not n:
return strs
lts = []
for i in range(1,n+1):
for j in permutations(strs,i):
flage = True #
for k in permutations(j): # , lts ,
# for k in permutations(j,i): #permutations, i,
k_strs = ''.join(k)
if k_strs in lts:
flage = False
break
if flage:
j_strs = ''.join(j)
lts.append(j_strs)
return lts
# 2
def zuHe2(strs):
n = len(strs)
if not n:
return strs
lts = []
for i in range(1,n+1):
for j in combinations(strs,i):
flage = True #
# , lts , combinations i
for k in combinations(j,i):
k_strs = ''.join(k)
if k_strs in lts:
flage = False
break
if flage:
j_strs = ''.join(j)
lts.append(j_strs)
return lts
# ,
for m in product([1,2],repeat=3):
print(m)
'''
(1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 2, 2)
(2, 1, 1)
(2, 1, 2)
(2, 2, 1)
(2, 2, 2)
'''
if __name__ == '__main__':
print(zuHe(strs)) #['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
print(zuHe2(strs)) #['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']