排列
def
perm
(
arr
,
stack
)
:
if
not
arr
:
print
(
stack
)
# 到树的最后,输出结果
tmp
=
stack
.
copy
(
)
res
.
append
(
tmp
)
else
:
# 没有到树的叶子节点的时候,使用递归继续往下找。
for
i
in
range
(
len
(
arr
)
)
:
stack
.
append
(
arr
[
i
]
)
del
arr
[
i
]
perm
(
arr
,
stack
)
arr
.
insert
(
i
,
stack
.
pop
(
)
)
arr
=
[
1
,
2
,
3
]
stack
=
[
]
res
=
[
]
perm
(
arr
,
stack
)
print
(
res
)
def
str_sort
(
s
=
''
)
:
if
len
(
s
)
<=
1
:
return
[
s
]
str_list
=
[
]
for
i
in
range
(
len
(
s
)
)
:
for
j
in
str_sort
(
s
[
0
:
i
]
+
s
[
i
+
1
:
]
)
:
str_list
.
append
(
s
[
i
]
+
j
)
return
str_list
str_list
=
str_sort
(
"123"
)
print
(
str_list
)
组合
import
itertools
# itertools.combinations()
def
combinations
(
iterable
,
r
)
:
pool
=
tuple
(
iterable
)
n
=
len
(
pool
)
if
r
>
n
:
return
indices
=
list
(
range
(
r
)
)
yield
tuple
(
pool
[
i
]
for
i
in
indices
)
while
True
:
for
i
in
reversed
(
range
(
r
)
)
:
if
indices
[
i
]
!=
i
+
n
-
r
:
break
else
:
return
indices
[
i
]
+=
1
for
j
in
range
(
i
+
1
,
r
)
:
indices
[
j
]
=
indices
[
j
-
1
]
+
1
yield
tuple
(
pool
[
i
]
for
i
in
indices
)
if
__name__
==
'__main__'
:
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
for
i
in
combinations
(
range
(
1
,
5
)
,
2
)
:
print
(
i
)