Application of Permutation and Combination

发布时间 2023-06-08 16:45:59作者: Mysticbinary

Reference

https://www.shuxuele.com/combinatorics/combinations-permutations.html

Online Tool

https://gadget.chienwen.net/x/math/percomb

Cracking the Safe!

假设你要暴力破解一个保险箱,密码只有4位,每位有0-9个可能,请思考怎么破解呢?
这个密码排列的特征是:

  • 次序重要
  • 可重复

那么就选重复排列方式计算即可。

Code:

import itertools

product_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
product = list(itertools.product(product_list, repeat=4))
print("product number :", len(product))
print("product list: ", product)

# out:
product number : 10000
product list:  [(1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 1, 3), (1, 1, 1, 4) ... ]

计算比赛前三名有多少种排列方式?

有一场比赛,分别有A,B,C,D,E,F,G,H共8支队伍参加,现在想算到时得前三名的排列情况有多少种?
这个名次排列的特征:

  • 次序重要
  • 不可以重复

那么就选不重复排列方式计算即可。

from itertools import permutations

itering = permutations(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 3)
plist = list(itering)
print("前三名的排列有多少种: ", len(plist))
print("permutations list: ", plist)

# 前三名的排列有多少种: 336
# permutations list:  [('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'B', 'E'), ('A', 'B', 'F'), ... ]

Can you win the lottery?

假设彩票的玩法是从编号为01~33个球中随机抽出6个,顺序不重要。你选6个数组合成一注彩票,如果所选的6个号码都中了,就表示你中了1等奖。
那么有多少种组合情况?

这个中奖号码组合的特征:

  • 次序不重要
  • 不可重复

用不可重复组合求即可。

from itertools import combinations, permutations
from scipy.special import comb, perm

C = comb(33, 6)
# out: C = 3.0
print("combinations number: ", C)

itering = combinations(
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
     32, 33], 6)
Clist = list(itering)
with open('temp.txt', 'w') as f:
    for i in Clist:
        f.writelines(str(i) + "\r")
# out:
combinations number:  1107568.0

out:

如何做仙丹?

假设有个神仙要你用5种材料('人参', '萝卜', '火龙果', '鹿茸', '熊掌')做一个仙丹,需要按照特定的配方,但是配方不告诉你,只告诉你做的规则,顺序无所谓,可以有重复,正确的只有一种配方。
你知道你要尝试多少次才能做出仙丹?

这个配方组合的特征:

  • 次序不重要
  • 可重复

用重复组合求即可。

c_list = ['人参', '萝卜', '火龙果', '鹿茸', '熊掌']
clist = list(itertools.combinations_with_replacement(c_list, 3))

print("一共有多少种组合: ", len(clist))
print("List: ", clist)

#out:
一共有多少种组合:  35
List:  [('人参', '人参', '人参'), ('人参', '人参', '萝卜'), ('人参', '人参', '火龙果'), ('人参', '人参', '鹿茸'), ('人参', '人参', '熊掌')...]

Think

Do you know any other application scenarios?
TODO

Permutation Concept

TODO

Combination Concept

TODO