Menghasilkan nomor urut unik dengan python

Artikel ini adalah tentang modul

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
5 dengan Python, yang digunakan untuk menghasilkan angka acak semu untuk berbagai distribusi probabilistik


Metode Modul acak Python

1. benih()

Ini menginisialisasi generator nomor acak. Untuk menghasilkan urutan acak baru, benih harus diatur tergantung pada waktu sistem saat ini.

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
6 menetapkan benih untuk pembuatan angka acak

2. getstate()

Ini mengembalikan objek yang berisi keadaan generator saat ini. Untuk memulihkan status, teruskan objek ke

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
7

3. setstate(status_obj)

Ini mengembalikan status generator pada saat

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
8 dipanggil, dengan meneruskan objek status

4. getrandbits(k)

Ini mengembalikan bilangan bulat Python dengan

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
_9 bit acak. Ini berguna untuk metode seperti
Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868
_0 untuk menangani rentang besar yang berubah-ubah untuk pembuatan angka acak

>>> import random
>>> random.getrandbits(100) # Get a random integer having 100 bits
802952130840845478288641107953
_

Berikut adalah contoh untuk mengilustrasikan metode

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
_8 dan
import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
7

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

Kemungkinan Keluaran

Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868


Hasilkan Bilangan Bulat Acak

Modul acak menyediakan beberapa metode khusus untuk menghasilkan bilangan bulat acak

1. randrange (mulai, berhenti, langkah)

Mengembalikan bilangan bulat yang dipilih secara acak dari

Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868
3. Ini menimbulkan
Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868
4 jika
Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868
5 >
Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868
6

2. randint(a, b)

Mengembalikan bilangan bulat acak antara a dan b (keduanya inklusif). Ini juga menimbulkan

Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868
4 jika
Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868
8 >
Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868
9

Berikut adalah contoh yang menggambarkan kedua fungsi di atas

import random

i = 100
j = 20e7

# Generates a random number between i and j
a = random.randrange(i, j)
try:
    b = random.randrange(j, i)
except ValueError:
    print('ValueError on randrange() since start > stop')

c = random.randint(100, 200)
try:
    d = random.randint(200, 100)
except ValueError:
    print('ValueError on randint() since 200 > 100')

print('i =', i, ' and j =', j)
print('randrange() generated number:', a)
print('randint() generated number:', c)

Kemungkinan Keluaran

ValueError on randrange() since start > stop
ValueError on randint() since 200 > 100
i = 100  and j = 200000000.0
randrange() generated number: 143577043
randint() generated number: 170


Menghasilkan angka floating point acak

Mirip dengan menghasilkan bilangan bulat, ada fungsi yang menghasilkan urutan floating point acak

  • acak. random() -> Mengembalikan angka floating point acak berikutnya antara [0. 0 sampai 1. 0)
  • acak. uniform(a, b) -> Mengembalikan floating point acak
    import random
    
    i = 100
    j = 20e7
    
    # Generates a random number between i and j
    a = random.randrange(i, j)
    try:
        b = random.randrange(j, i)
    except ValueError:
        print('ValueError on randrange() since start > stop')
    
    c = random.randint(100, 200)
    try:
        d = random.randint(200, 100)
    except ValueError:
        print('ValueError on randint() since 200 > 100')
    
    print('i =', i, ' and j =', j)
    print('randrange() generated number:', a)
    print('randint() generated number:', c)
    
    0 sehingga a <= N <= b if a <= b and b <= N <= a if b < a
  • acak. expovariate(lambda) -> Mengembalikan angka yang sesuai dengan distribusi eksponensial
  • acak. gauss(mu, sigma) -> Mengembalikan angka yang sesuai dengan distribusi gaussian

Ada fungsi serupa untuk distribusi lain, seperti Distribusi Normal, Distribusi Gamma, dll

Contoh menghasilkan angka titik-mengambang ini diberikan di bawah ini

import random

print('Random number from 0 to 1 :', random.random())
print('Uniform Distribution between [1,5] :', random.uniform(1, 5))
print('Gaussian Distribution with mean = 0 and standard deviation = 1 :', random.gauss(0, 1))
print('Exponential Distribution with lambda = 0.1 :', random.expovariate(0.1))
print('Normal Distribution with mean = 1 and standard deviation = 2:', random.normalvariate(1, 5))

Kemungkinan Keluaran

Random number from 0 to 1 : 0.44663645835100585
Uniform Distribution between [1,5] : 3.65657099941547
Gaussian Distribution with mean = 0 and standard deviation = 1 : -2.271813609629832
Exponential Distribution with lambda = 0.1 : 12.64275539117617
Normal Distribution with mean = 1 and standard deviation = 2 : 4.259037195111757


Urutan Acak menggunakan modul acak

Mirip dengan bilangan bulat dan urutan titik-mengambang, urutan generik dapat berupa kumpulan item, seperti Daftar/Tuple. Modul

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
5 menyediakan fungsi berguna yang dapat memperkenalkan keadaan acak ke urutan

1. acak. acak (x)

Ini digunakan untuk mengocok urutan di tempat. Urutan dapat berupa daftar/tuple yang mengandung elemen

Contoh Kode untuk mengilustrasikan pengocokan

import random

sequence = [random.randint(0, i) for i in range(10)]

print('Before shuffling', sequence)

random.shuffle(sequence)

print('After shuffling', sequence)

Kemungkinan Keluaran

Before shuffling [0, 0, 2, 0, 4, 5, 5, 0, 1, 9]
After shuffling [5, 0, 9, 1, 5, 0, 4, 2, 0, 0]

2. acak. pilihan(seq)

Ini adalah fungsi yang banyak digunakan dalam praktik, di mana Anda ingin mengambil item secara acak dari Daftar/urutan

import random

a = ['one', 'eleven', 'twelve', 'five', 'six', 'ten']

print(a)

for i in range(5):
    print(random.choice(a))

Kemungkinan Keluaran

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
0

3. acak. sampel(populasi, k)

Mengembalikan sampel acak dari urutan panjang

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
9

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
_1

Kemungkinan Keluaran

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
_2


Benih Acak

Karena pembuatan pseudorandom didasarkan pada nomor sebelumnya, kami biasanya menggunakan waktu sistem untuk memastikan bahwa program memberikan keluaran baru setiap kali kami menjalankannya. Oleh karena itu, kami menggunakan

import random

i = 100
j = 20e7

# Generates a random number between i and j
a = random.randrange(i, j)
try:
    b = random.randrange(j, i)
except ValueError:
    print('ValueError on randrange() since start > stop')

c = random.randint(100, 200)
try:
    d = random.randint(200, 100)
except ValueError:
    print('ValueError on randint() since 200 > 100')

print('i =', i, ' and j =', j)
print('randrange() generated number:', a)
print('randint() generated number:', c)
_3

Python memberi kita

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
_6 yang dengannya kita dapat menetapkan benih untuk mendapatkan nilai awal. Nilai seed ini menentukan keluaran dari generator bilangan acak, jadi jika tetap sama, keluarannya juga tetap sama

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
_3

Kemungkinan Keluaran

import random

random.seed(1)

# Get the state of the generator
state = random.getstate()

print('Generating a random sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))

# Restore the state to a point before the sequence was generated
random.setstate(state)
print('Generating the same identical sequence of 3 integers...')
for i in range(3):
    print(random.randint(1, 1000))
_4

Hal ini memastikan bahwa kita perlu berhati-hati terhadap seed kita saat berhadapan dengan urutan pseudorandom, karena urutan tersebut dapat berulang jika seed tidak berubah.


Kesimpulan

Kami belajar tentang berbagai metode yang disediakan oleh modul acak Python, untuk berurusan dengan bilangan bulat, bilangan titik-mengambang, dan urutan lain seperti Daftar, dll. Kami juga melihat bagaimana seed memengaruhi urutan nomor pseudorandom

Bagaimana Anda mencetak angka secara berurutan dengan Python?

Fungsi Python range() mengembalikan urutan angka, dalam rentang tertentu . Penggunaannya yang paling umum adalah untuk mengulangi urutan pada urutan angka menggunakan loop Python.

Bagaimana Anda menghasilkan nomor acak tanpa duplikat di Python?

Gunakan fungsi randint()(Mengembalikan angka acak dalam rentang yang ditentukan) dari modul acak , untuk menghasilkan angka acak dalam rentang dalam rentang yang ditentukan i. e.dari 1 sampai 100.

Bagaimana Anda menghasilkan angka acak 12 digit dengan Python?

Anda harus menggunakan acak. randint(10**11, 10**12-1) sebagai gantinya.

Bagaimana Anda menghasilkan angka acak dengan pengulangan di Python?

1 Jawaban .
impor acak [acak. randint(1.100) untuk x dalam rentang(2000)]
impor acak x = [acak. randint(1.100) untuk x dalam rentang(2000)] cetak x
impor acak [acak. randint(50.100) untuk x dalam rentang(2000)]