“sample larger than population” in random.sample python

前端 未结 3 1993
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 00:31

creating a simple pass generator for myself, i noticed that if i want my population to be digits only (0-9) which is overall 10 options, if i want my length over 10, it wont

3条回答
  •  不知归路
    2020-12-16 01:07

    The purpose of random.sample() is to pick a subset of the input sequence, randomly, without picking any one element more than once. If your input sequence has no repetitions, neither will your output.

    You are not looking for a subset; you want single random choices from the input sequence, repeated a number of times. Elements can be used more than once. Use random.choice() in a loop for this:

    for i in range(y):
        string = ''.join([random.choice(x) for _ in range(v)])
        print string
    

    This creates a string of length v, where characters from x can be used more than once.

    Quick demo:

    >>> import string
    >>> import random
    >>> x = string.letters + string.digits + string.punctuation
    >>> v = 20
    >>> ''.join([random.choice(x) for _ in range(v)])
    'Ms>V\\0Mf|W@R,#/.P~Rv'
    >>> ''.join([random.choice(x) for _ in range(v)])
    'TsPnvN&qlm#mBj-!~}3W'
    >>> ''.join([random.choice(x) for _ in range(v)])
    '{:dfE;VhR:=_~O*,QG

提交回复
热议问题