Python Forum
Generate random id (please help!)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Generate random id (please help!)
#1
Hi All!

I need to write a function that returns a random id for an employee. Can anybody tell me why it returns... "None"? I'm stuck with it...

import random
import string

def generate_id(number_of_small_letters=4,
                number_of_capital_letters=2,
                number_of_digits=2,
                number_of_special_chars=2,
                allowed_special_chars=r"_+-!"):
    
    small_letters = string.ascii_lowercase
    capital_letters = string.ascii_uppercase
    digits = "0123456789"
    
    
    result_small = ''.join(random.choice(small_letters) for i in range (number_of_small_letters))
    result_capital = ''.join(random.choice(capital_letters) for i in range (number_of_capital_letters))
    result_digits = ''.join(random.choice(digits) for i in range (number_of_digits))
    result_special_characters = ''.join(random.choice(allowed_special_chars) for i in range (number_of_special_chars))
    
    random_characters = result_digits + result_small + result_capital + result_special_characters
    
    random_characters_list = list(random_characters.strip(" "))
   
    final_result = random.shuffle(random_characters_list)
    
    return str(final_result)
    
Reply
#2
The function random.shuffle() returns None. Try
return ''.join(random_character_list)
Kjaglewicz likes this post
Reply
#3
(Aug-22-2022, 06:23 PM)Kjaglewicz Wrote: Can anybody tell me why it returns... "None"?


Hi.

The shuffle() method takes a sequence (such as your list) and reorganizes the order of the items, in place and as such final_result = random.shuffle(random_characters_list) is simply None, which is what is returned.

Change that line to random.shuffle(random_characters_list)
The object you need in your return is the random_characters_list.
Kjaglewicz likes this post
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#4
(Aug-22-2022, 06:42 PM)Gribouillis Wrote: The function random.shuffle() returns None. Try
return ''.join(random_character_list)

Thank you, it works, but tere are another 2 problems:
1. it has to be shuffled (the characters)
2. it has to return string instead of list
Reply
#5
"".join(random+character_list) creates a str by joining all the str in random_character_list separated by "".

random.shuffle(random_characters_list)
Shuffles the strings in random_characters_list. Your problem was the shuffle is done "in place" and the function returns None.

Together:
random.shuffle(random_characters_list)
return "".join(random_characters_list)
Kjaglewicz likes this post
Reply
#6
(Aug-22-2022, 07:11 PM)deanhystad Wrote: trings in random_characters_list. Your problem was the shuffle
THANK YOU!!!!
Reply
#7
Another way of doing it

# Do the imports
from random import sample, shuffle
import string

# define the function
def generate_id():
    ''' Get the needed sample characters and size using string '''
    small_letters = sample(string.ascii_lowercase, 4)
    capital_letters = sample(string.ascii_uppercase, 2)
    numbers = sample(string.digits, 2)
    special_characters = sample('_+-!', 2)

    # Combine and shuffle samples
    result = small_letters + capital_letters + numbers + special_characters
    shuffle(result)

    # Return the results
    return ''.join(result)

for i in range(5):
    print(generate_id())
Output:
+Gr5-pgN2u cgOh4-2Gq+ 6F!Xi+ztw7 +xb3Z1Gvp- mF7!h_snG5
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#8
Just for fun, I thought I'd try without random.

If you get the time in epoch seconds, you have a random seed to start with.

def myApp():
    import string
    import time

    # characters to choose from
    source = string.ascii_lowercase + '#%&_*!?' + string.ascii_uppercase + '0123456789ABCDEF'
    # the current time in epoch seconds
    t = time.time()
    print('Time:', t)
    # t looks like 1661347380.6547987
    mystring = str(t)
    mylist = mystring.split('.')
    # the last numbers change faster so mix them up
    mynumstr = mylist[1] + mylist[0] + mylist[1] + mylist[0]
    # divide by any number
    mynum = int(mynumstr) / 7
    start = str(int(mynumstr))
    # start looks like '9736476166135020597364761661350205'
    # start must be more than 2 * the length of the pasword required or index error
    password = ''
    # how long do you want the password?
    # 30 gives you a password of 15 characters 
    for i in range(0, 30, 2):
        # if num begins with zero no problem, int() junks the leading zero
        num = int(start[i:i+2])
        print(num)
        while num > len(source):
            num = int(num / 2)
        password = password + source[int(num)]

    print('Your shiny new password is', password)
Reply
#9
(Aug-22-2022, 06:23 PM)Kjaglewicz Wrote: Hi All!

I need to write a function that returns a random id for an employee. Can anybody tell me why it returns... "None"? I'm stuck with it...

import random
import string

def generate_id(number_of_small_letters=4,
                number_of_capital_letters=2,
                number_of_digits=2,
                number_of_special_chars=2,
                allowed_special_chars=r"_+-!"):
    
    small_letters = string.ascii_lowercase
    capital_letters = string.ascii_uppercase
    digits = "0123456789"
    
    
    result_small = ''.join(random.choice(small_letters) for i in range (number_of_small_letters))
    result_capital = ''.join(random.choice(capital_letters) for i in range (number_of_capital_letters))
    result_digits = ''.join(random.choice(digits) for i in range (number_of_digits))
    result_special_characters = ''.join(random.choice(allowed_special_chars) for i in range (number_of_special_chars))
    
    random_characters = result_digits + result_small + result_capital + result_special_characters
    
    random_characters_list = list(random_characters.strip(" "))
   
    final_result = random.shuffle(random_characters_list)
    
    return str(final_result)
    

Taking a step back and breaking the problem into smaller pieces is always a good idea when you bump up against something that doesn't work the way you expect it to.

Here's one approach that leverages the Python interactive interpreter:

>>> import random
>>> import string
>>>
>>> number_of_small_letters=4
>>> small_letters = string.ascii_lowercase
>>>
>>> result_small = ''.join(random.choice(small_letters) for i in range (number_of_small_letters))
>>> result_small
'tjso'
>>>
>>> random_characters = result_small
>>> random_characters_list = list(random_characters.strip(" "))
>>> random_characters_list
['t', 'j', 's', 'o']
>>>
>>> r = random.shuffle(random_characters_list)
>>> r
>>> 
>>> repr(r)
'None'
>>>
>>> random_characters_list
['s', 'o', 'j', 't']
>>> 
>>> help(random.shuffle)
Help on method shuffle in module random:

shuffle(x, random=None) method of random.Random instance
    Shuffle list x in place, and return None.

    Optional argument random is a 0-argument function returning a
    random float in [0.0, 1.0); if it is the default None, the
    standard random.random will be used.


Per the output of help(), the shuffle method worked exactly as advertised.

Shuffle list x in place, and return None.


Hopefully, the investigative work above would have pointed you towards the solution called out by @Gribouillis and @deanhystad :

return "".join(random_characters_list)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Generate random hex number ZYSIA 1 11,631 Jul-16-2021, 09:21 AM
Last Post: DeaD_EyE
  Generate Random operator, take user input and validate the user mapypy 4 5,575 Feb-03-2021, 08:41 PM
Last Post: nilamo
  Generate only one random number for many tries Bhavika 2 1,754 Mar-29-2020, 12:12 PM
Last Post: Bhavika
  Can i prevent the random generator to generate already used numbers? MauserMan 3 2,892 Jan-05-2020, 04:44 PM
Last Post: MauserMan
  generate random variables based on a non-standard t-distribution nathalie 4 3,456 Dec-03-2019, 12:11 AM
Last Post: scidam
  Need to generate random numbers Gateux 8 3,956 Jul-19-2019, 03:37 PM
Last Post: Man_from_India
  Generate unique random numbers from different lists Takeshio 5 3,795 May-24-2019, 07:29 PM
Last Post: ichabod801
  how to generate random 3d world (like minecraft) in python hsunteik 3 101,599 Jan-06-2017, 06:35 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020