如何从 Ruby/Python 中的 2 个数字 n 和 k 写组合和排列?

How to write Combination and Permutation from 2 numbers n and k in Ruby/Python?

例如,如果我有 100 只可区分的狗,我想随机挑选其中的 3 只。使用袖珍型计算器,我会做 100C3 或类似的计算。我如何在 Ruby 和 Python 中执行此操作?

第 1 版:我的问题已通过 Razvans 和 Riccardo Bucco 解决方案解决。 (我掷了一次公平的硬币来决定我给谁打勾,给谁点赞)。

谢谢大家

您将在 python 中执行此操作:

from math import comb

n_combinations = comb(100, 3)

同样,对于排列:

from math import perm

n_permutations = perm(100, 3)

permcomb 只能与 python > 3.8 一起使用。对于 python 的旧版本,请使用这些函数:

from math import factorial

def comb(n, k):
    return factorial(n) // factorial(k) // factorial(n - k)

def perm(n, k=None):
    return factorial(n) // factorial(n - (k or n))

Ruby 有 combination (and permutation):

(0...100).to_a.combination(3).to_a
(0...100).to_a.permutation(3).to_a

但是如果你想从那个数组中随机挑选 3 条狗,则有 sample:

(0...100).to_a.sample(3)
在 python 中从 100 条狗中随机选择 3 条狗而不放回:

假设这个预先存在的列表:

dogs = [f'dog{i+1}' for i in range(100)]
# ['dog1', 'dog2', 'dog3', ..., 'dog100']

你可以使用 random.sample

import random
random.sample(dogs, k=3)

可能的输出:['dog56', 'dog13', 'dog59']

Ruby 的数组方法 combinationrepeated_combinationpermutationrepeated_permutation 都是 return 枚举器。枚举器有一个 size 方法,它 return 是枚举器的大小,如果不能延迟计算则为 nil 。很高兴在这些情况下他们可以,例如:

#How many ways to take 12 random dogs out of 1000 :
puts (1..1000).to_a.combination(12).size # 1953840414726664053684327000