The problem
You’re creating a picture internet hosting web site.
It’s important to create a operate for producing random and distinctive picture filenames.
Create a operate for producing a random 6 character string that can be used to entry the photograph URL.
To ensure the title just isn’t already in use, you might be given entry to a PhotoManager object.
You’ll be able to name it like so to ensure the title is exclusive
# at this level, the web site has just one photograph, hosted on the 'ABCDEF' url
photoManager.nameExists('ABCDEF'); # returns true
photoManager.nameExists('BBCDEF'); # returns false
Word: We contemplate two names with the identical letters however totally different circumstances to be distinctive.
The answer in Python code
Choice 1:
import uuid
def generateName():
return str(uuid.uuid4())[:6]
Choice 2:
from random import pattern
from string import ascii_letters
def generateName(size=6):
whereas True:
title = ''.be part of(pattern(ascii_letters, size))
if not photoManager.nameExists(title):
return title
Choice 3:
generateName=lambda:str(__import__("time").time())[-6:]
Take a look at circumstances to validate our answer
for i in vary(10):
title = generateName();
check.count on(isinstance(title, str), "Title needs to be a string.");
check.count on(photoManager.nameWasUnique(title), "Title needs to be distinctive.");
check.assert_equals(len(title), 6, "Title needs to be 6 digits lengthy.");