Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate alphanumeric random numbers in numpy

I want random numbers 100000+, I found numpy is suitable for my project based on performance it is good. But I want 4 places random number based on below pattern,

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

In the above case 26 small letters,26 capital letters and 10 digits equal to 62 total letters and let us take permutation and combinations,

I want 4 digits from those letters so,

62 ^ 4 / 4! = 615680 (Combinations)

If I take 26 small letters + 10 digits and the output is,

(26+10) ^ 4 / 4! = 69984 (Combinations)

From those two cases first one is best, It provides better random numbers, I did some logic here,

from numpy.random.mtrand import RandomState
import binascii
lo = 1000000000000000
hi = 999999999999999999
In [65]: %timeit [ binascii.b2a_hex(rand.randint(lo, hi, 2).tostring())[:4] for _ in xrange(100000)]
1 loops, best of 3: 272 ms per loop

But the random number count is below 100000, Because it only takes small lettes + digits

In [66]: len(set([binascii.b2a_hex(rand.randint(lo, hi, 2).tostring())[:4] for _ in xrange(100000)]))
Out[66]: 51210

Any one suggest me how to implement this in numpy ?

like image 961
dhana Avatar asked Jul 11 '26 06:07

dhana


2 Answers

As pointed out by NPE, you can use numpy.random.choice. Does this code achieve what you want?

import numpy as np

LENGTH = 4
NO_CODES = 100000

alphabet = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
np_alphabet = np.array(alphabet, dtype="|S1")
np_codes = np.random.choice(np_alphabet, [NO_CODES, LENGTH])
codes = ["".join(np_codes[i]) for i in range(len(np_codes))]

print(codes)

It takes a couple of seconds to execute with NO_CODES = 1000000 on my 2-years-old but not bad computer.

like image 73
marcotama Avatar answered Jul 13 '26 21:07

marcotama


It can be done much faster by using numpy view.

A, Z = np.array(["A","Z"]).view("int32") 

NO_CODES = 100
LEN = 20

np.random.randint(low=A,high=Z,size=NO_CODES*LEN,dtype="int32").view(f"U{LEN}")
like image 42
Ales Novak Avatar answered Jul 13 '26 19:07

Ales Novak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!