算法相关问题[Python基础]

1.排列组合问题:

需要用到Python的itertools模块

import itertools
a=[1,2,3]

#排列,无放回的取,排列(数学公式:A32的意思)
for i in itertools.permutations(a,2):#2是拿两次,a可以是字符串或者是列表
    print(i)

"""
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
"""

#组合,无放回的取,组合(数学公式:C32的意思)
# for i in itertools.combinations(a,2):
#     print(i)
"""
(1, 2)
(1, 3)
(2, 3)
"""

#有放回的排列(笛卡尔积)
# for i in itertools.product(a,repeat=2):
#     print(i)

"""
(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)
"""

#有放回的组合
# for i in itertools.combinations_with_replacement(a, 2):
#     print(i)
"""
(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)
"""
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 算法相关问题