-1

Sample:

import random as r  
ph_no = []
ph_no.append(r.randint(6, 9))
for i in range(1, 10):
    ph_no.append(r.randint(0, 9))
for i in ph_no:
    print(i, end="")

output:

* 9735969745
* 6882962314

here it is but it should be unique number generation any help ???

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
  • It will be better to follow the AUTOINCREMENT approach and set an offset for your first bank account. – Sachin Kumar Jan 21 '23 at 05:01
  • That will make bank account prediction possible while the OP is asking for random generation. Agreed that it should be a job for a Database at least for the storage, persistence and the uniqueness assessment. – jlandercy Jan 21 '23 at 05:50
  • 1
    Generating a 10-digit random number is trivial. However, what do you propose to do to prove its uniqueness? What are your terms of reference? – DarkKnight Jan 21 '23 at 07:20
  • Do you mean you just want each number you generate to be different than all the others you've generated so far? Just in this session, or ever? – CrazyChucky Jan 21 '23 at 07:46

5 Answers5

0

The account number shall be stored in a database and the column shall be unique. Then everytime the system creates a new account, it shall check if the account number exits.

But maybe you are doing this for testing purpose, you can use uuid4 to generate and assume it is unique. Or check it before creating just for testing:

accounts = set()
for i in range(10):
    while True:
        num = random_number()
        if num not in set:
            accounts.add(num)
            break
Mas Zero
  • 503
  • 3
  • 16
  • okay then likewise i need to generate pin number but i can't use uuid any idea? – PRAWIN KUMAR Jan 21 '23 at 05:18
  • @PRAWINKUMAR The above codes is generating 10 unique integers. Just use your code in random_number() function – Mas Zero Jan 21 '23 at 05:25
  • PIN number are very low entropy security code, you can't keep it unique before the possible number of accounts, a properly generated random number for PIN is the best thing you can do. – jlandercy Jan 21 '23 at 05:30
0

You can check the existing posts which should be of help.. How to generate unique 8 length number, for account ID for example (Python,Django)

Below code is from the above post, I have tested it and it works as expected.

import random
import string
print(''.join(random.choice(string.digits) for _ in range(8)))

this would give you a random 8 digit string, however depending on what your usecase is, You need to add the validation of checking if this random number exist. If its a DB entry then you have to check with the particular table column in the DB.

If its on the code level only you can use a for loop with where ever you are storing the dataset.

In my opinion, If this is related to a DB, increment your existing PK account number value by some number and you should be good.

Aniket
  • 35
  • 7
0

There are two clear requirements in your problem:

  • Randomness: Generate random account number with a specific pattern
  • Uniqueness: Ensure new account number is unique (not yet used)

While a real life application will certainly delegate part of the job to a database, here is a simple solution in pure python with minimal complexity:

import random


class Bank:
    
    def __init__(self):
        self.accounts = set()
    
    @staticmethod
    def get_random_account():
        prefix = random.randint(10, 99)
        number = random.randint(1e9, 1e10 - 1)
        check = int((prefix * 1e10) + number) % 97
        return f"{prefix:0>2d}-{number:0>10d}-{check:0>2d}"
    
    def create_account(self):
        while True:
            account = self.get_random_account()
            if account not in self.accounts:
                self.accounts.add(account)
                return account

I fix the random seed to a known value in order to make the MCVE reproducible:

random.seed(123)  # Comment this line for more randomness

We create a Bank object that will be in charge for both operations: random account generation (static method) and unique account number creation (created account storage).

my_bank = Bank()

You can always create a random account without checking it is unique (not already issued):

my_bank.get_random_account() # '16-2149664691-72'

Then we can issue 10 account numbers that are guaranteed to be unique among this bank instance:

for _ in range(10):
    account = my_bank.create_account()
    print(account)

# 62-2144839923-10
# 14-7710107789-37
# 53-4659684175-93
# 30-5875034668-84
# 81-2052968588-52
# 10-9185802068-43
# 21-2621757232-66
# 10-2925527091-15
# 15-9988355352-16
# 28-4893851635-83

If we check the accounts attribute of the instance we can confirm those issued account are stored in the set to allow uniqueness assessment:

my_bank.accounts

# {'10-2925527091-15',
# '10-9185802068-43',
# '14-7710107789-37',
# '15-9988355352-16',
# '21-2621757232-66',
# '28-4893851635-83',
# '30-5875034668-84',
# '53-4659684175-93',
# '62-2144839923-10',
# '81-2052968588-52'}

When using a set the order of issued accounts is not preserved. Insertion order was ignored as it was not part of the requirements. Anyway changing set for a dict is easy an can both be used to preserve creation order (since 3.7+) and store a randomly generated PIN number as well. Let's do it:

class Bank:
    
    def __init__(self):
        self.accounts = dict()
    
    @staticmethod
    def get_random_account():
        prefix = random.randint(10, 99)
        number = random.randint(1e9, 1e10 - 1)
        check = int((prefix * 1e10) + number) % 97
        return f"{prefix:0>2d}-{number:0>10d}-{check:0>2d}"
    
    def create_account(self):
        while True:
            account = self.get_random_account()
            if account not in self.accounts:
                self.accounts[account] = {"pin": "{:0>4}".format(random.randint(0, 9999))}
                return account

Then our ten accounts would look like:

# {'62-2144839923-10': {'pin': '0625'},
# '58-6721745545-12': {'pin': '0850'},
# '30-5875034668-84': {'pin': '9190'},
# '52-4013734705-55': {'pin': '2683'},
# '10-9185802068-43': {'pin': '1435'},
# '86-2621757232-50': {'pin': '0108'},
# '50-8439051955-85': {'pin': '1671'},
# '15-9988355352-16': {'pin': '2329'},
# '26-5386175109-56': {'pin': '7055'},
# '83-7343337636-62': {'pin': '7688'}}
jlandercy
  • 7,183
  • 1
  • 39
  • 57
0

The simplest way to generate a pseudo random number of a certain length is to call random.randint() with appropriate upper and lower bounds. This also avoids unnecessary looping.

For example:

from random import randint

def genval(w):
    return str(randint(0, 10**w-1)).zfill(w)

print(f'Account number = {genval(10)}')
print(f'Pin number = {genval(4)}')

Sample output:

Account number = 4639019267
Pin number = 7007

Note:

The test for uniqueness is not implemented because the terms of reference have not been stated

DarkKnight
  • 19,739
  • 3
  • 6
  • 22
-1
import numpy as np

accounts = {} # store created bank accounts

# generate new bank account number dont call directly
def getAccount():
    return np.concatenate([[np.random.randint(6, 10)], np.random.randint(0, 10, size=9)])

# make sure bank account number is unique
def createAccount():
    found = False
    while not found:
        account = getAccount()
        str_account = "".join(map(str, account)) # converting list of int to string
        # print(str_account)
        if str_account not in accounts:
            found = True
            accounts[str_account] = None
            return account
            


account = createAccount()
print(account)

Using UUID

import uuid
account = str(uuid.uuid1().int>>64)[:10]
print(account)
Udesh
  • 2,415
  • 2
  • 22
  • 32
  • The logic is a bit complex: two loops including an infinite one to check the presence of an item in a sequence. Why not using set instead, it's built in and efficient. DRW – jlandercy Jan 21 '23 at 05:33
  • @jlandercy set doen't gurantee the order of elements – Udesh Jan 21 '23 at 05:40
  • Indeed it should only be used as an index to confirm existence/presence, a dict would keep the location if needed. Anyway there is no need of two loops to check the presence of an element in a list a single loop is enough. Look for the else branch of the for statement it will do the job of the outer undesirable while loop. – jlandercy Jan 21 '23 at 05:42
  • Thank @jlandercy it was complex I have removed the for loop it would be great if you can suggest how I can improve this logic further – Udesh Jan 21 '23 at 05:54