简体   繁体   中英

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

For example, if I have 100 distinguishable dogs and I want to randomly pick 3 of them. With a pocket-size calculator, I would do 100C3 or something similar. How can I do this in Ruby and Python?

Ruby has combination (and permutation ):

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

But if you randomly want to pick 3 dogs from that array, there is sample :

(0..100).to_a.sample(3)

You would do this in python:

from math import comb

n_combinations = comb(100, 3)

Similarly, for permutations:

from math import perm

n_permutations = perm(100, 3)

perm and comb can be used only with python > 3.8. For older versions of python please use these functions:

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))
Selecting 3 random dogs out of 100 without replacement in python:

Assuming this pre-existing list:

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

You could use random.sample

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

possible output: ['dog56', 'dog13', 'dog59']

Ruby's Array methods combination , repeated_combination , permutation and repeated_permutation all return Enumerators. Enumerators have a size method, which returns the size of the enumerator, or nil if it can't be calculated lazily. Happily in these cases they can, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM