developer tip

파이썬에서 특정 길이로 난수를 생성하는 방법

copycodes 2020. 9. 18. 08:20
반응형

파이썬에서 특정 길이로 난수를 생성하는 방법


3 자리 숫자가 필요하므로 다음과 같습니다.

>>> random(3)
563

or

>>> random(5)
26748
>> random(2)
56

임의의 3 자리 숫자를 얻으려면 :

from random import randint
randint(100, 999)  # randint is inclusive at both ends

( "최대 3 자리 숫자"가 아니라 실제로 3 자리 숫자를 의미한다고 가정합니다.)

임의의 자릿수를 사용하려면 :

from random import randint

def random_with_N_digits(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)

print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)

산출:

33
124
5127

문자열 (예 : 10 자리 전화 번호)로 원하는 경우 다음을 사용할 수 있습니다.

n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])

0은 가능한 첫 번째 숫자로 계산됩니까? 그렇다면 random.randint(0,10**n-1). 그렇지 않은 경우 random.randint(10**(n-1),10**n-1). 그리고 0이 허용 되지 않으면 0이있는 숫자를 명시 적으로 거부하거나 숫자를 그려야 n random.randint(1,9)합니다.

곁에 : randint(a,b)임의의 숫자를 얻기 위해 다소 파이썬 적이 지 않은 "인덱싱"을 사용 하는 것은 흥미 롭습니다 a <= n <= b. 사람은 그것처럼 작동 range하고 임의의 숫자를 생성 할 것으로 예상했을 a <= n < b있습니다. (닫힌 위쪽 간격에 유의하십시오.)

에 대한 코멘트에 응답을 감안할 때 randrange이러한 청소기로 대체 할 수 있습니다, random.randrange(0,10**n), random.randrange(10**(n-1),10**n)random.randrange(1,10).


3 자리 숫자가 필요하고 001-099가 유효한 숫자가되도록하려면 randrange / randint를 사용해야합니다. 이는 대안보다 빠릅니다. 문자열로 변환 할 때 필요한 선행 0을 추가하기 만하면됩니다.

import random
num = random.randrange(1, 10**3)
# using format
num_with_zeros = '{:03}'.format(num)
# using string's zfill
num_with_zeros = str(num).zfill(3)

또는 난수를 int로 저장하지 않으려면 oneliner로 수행 할 수 있습니다.

'{:03}'.format(random.randrange(1, 10**3))

파이썬 3.6+ 단 하나의 라이너 :

f'{random.randrange(1, 10**3):03}'

위의 출력 예는 다음과 같습니다.

  • '026'
  • '255'
  • '512'

함수로 구현 :

import random

def n_len_rand(len_, floor=1):
    top = 10**len_
    if floor > top:
        raise ValueError(f"Floor {floor} must be less than requested top {top}")
    return f'{random.randrange(floor, top):0{len_}}'

You could write yourself a little function to do what you want:

import random
def randomDigits(digits):
    lower = 10**(digits-1)
    upper = 10**digits - 1
    return random.randint(lower, upper)

Basically, 10**(digits-1) gives you the smallest {digit}-digit number, and 10**digits - 1 gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.


If you don't want to memorize all the different seemingly random commands (like myself) you can always use:

import random
Numbers = range(1, 10)
RandomNumber = random.choice(Numbers)
print(RandomNumber)
#returns a number

I really liked the answer of RichieHindle, however I liked the question as an exercise. Here's a brute force implementation using strings:)

import random
first = random.randint(1,9)
first = str(first)
n = 5

nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs))    :
    first += str(nrs[i])

print str(first)

From the official documentation, does it not seem that the sample() method is appropriate for this purpose?

import random

def random_digits(n):
    num = range(0, 10)
    lst = random.sample(num, n)
    print str(lst).strip('[]')

Output:

>>>random_digits(5)
2, 5, 1, 0, 4

You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:

import random

def generate_random_number(length):
    return int(''.join([str(random.randint(0,10)) for _ in range(length)]))

참고URL : https://stackoverflow.com/questions/2673385/how-to-generate-random-number-with-the-specific-length-in-python

반응형