My First Attempt :
def generate_id():
""" Create unique id of alphanumeric characters """
i = 0
id = ''
while i!=10:
id = id + random.choice(string.ascii_letters + string.digits)
i+=1
if check_unique(id):
return id
id = generate_id()
return id
def check_unique(id):
"""Check if id is unique"""
try:
instances = SomeModel.objects.get(id=id)
except ObjectDoesNotExist:
return True
return False
Second Way :
def generate_id():
""" Create unique id of alphanumeric characters """
i = 0
id = ''
while i!=10:
id = id + random.choice(string.ascii_letters + string.digits)
i+=1
if check_unique(id):
return id
generate_id()
def check_unique(id):
"""Check if id is unique"""
try:
instances = SomeModel.objects.get(id=id)
except ObjectDoesNotExist:
return True
return False
If I do it the second way , won't my logic of generating unique id's be wrong ? Because I might loose the id from the last call .
I am new to python and I don't know but I think my recursion
concept looks messed up
Follow your code:
if check_unique(id): # If this is `false`, you keep going
return id
generate_id() # Now what? You call the function. Nothing gets returned.
If you want to create a unique ID, don't use recursion. Just use a while
loop and generate new IDs as long as they're not unique:
characters = string.ascii_letters + string.digits
def generate_id(length=10):
return ''.join(random.choice(characters) for i in range(length))
def generate_unique_id(length=10):
id = generate_id(length)
while not check_unique(id):
id = generate_id(length)
return id
In the second way you should return a the end of the generate_id function:
return generate_id()
I would also suggest to make an iteration instead of a recursive call... it's seems cleaner in this situation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.