Home > database >  Generate random User ID with a function ; including quantity_digits and quantity_list being provided
Generate random User ID with a function ; including quantity_digits and quantity_list being provided

Time:03-24

Please note I am only allowed to use Math and Random class

so for this, I was considering using "for loop" for the number of of digits restriction from quantity_digit and use ''.join() function to add things up. The list might be like this ["333322","999883"].

I was wondering how do I for each iteration, randomly pick an element and within that element, pick random number from it. Can this be done? Please help

so this is I want to do

  1. define the function 2)for loop for addition of the characters from the string
  2. choose random string from the list each iteration
  3. and (each iteration) in that list I want to select several characters from that specific String
  4. use join() function to add things up

CodePudding user response:

ok this is a fairly basic solution, u can add modifications to it

from random import choices
from string import digits

password = lambda quantity_digit, quantity_list: [''.join(choices(digits, k=quantity_digit)) for _ in range(quantity_list)]
print(password(10, 2))

CodePudding user response:

i guess this is a more beginner friendly answer

import random

def random_password(quantity_digit, quantity_list):
    main_list = []
    for i in range(quantity_list):
        temp_string = ''
        for j in range(quantity_digit):
            temp_string  = random.choice('1234567890')
        main_list.append(temp_string)
    
    return main_list

Explaination

  • generating an empty list to which we will add the random number
  • in the first for loop, we are generating an empty string
  • then we are adding random numbers to the empty string (quantity_digit times)
  • then we are adding this string to the main_list

Demonstartion

print(random_password(10, 2))

output:

['5810832344', '5716136790']
print(''.join(random_password(10, 2)))

output:

87651084999133098434

CodePudding user response:

My understanding of the problem is this... You have a list of strings. Each string contains some digits. You want to make a 'password' by randomly selecting one of the strings in your reference list and then randomly selecting one of the digits from that string. You want to be able to specify a length of the resulting string.

If that's the case then:

from random import choice

reference = ['333322', '999883']

def make_password(ref, length):
    return ''.join(choice(choice(ref)) for _ in range(length))

print(make_password(reference, 6))

Output: (example)

292393
  • Related