Skip to content

How to create an Image Host Filename Generator in Python

The challenge

You are developing an image hosting website.

You have to create a function for generating random and unique image filenames.

Create a function for generating a random 6 character string that will be used to access the photo URL.

To make sure the name is not already in use, you are given access to a PhotoManager object.

You can call it like so to make sure the name is unique

# at this point, the website has only one photo, hosted on the 'ABCDEF' url photoManager.nameExists('ABCDEF'); # returns true photoManager.nameExists('BBCDEF'); # returns false
Code language: Python (python)

Note: We consider two names with the same letters but different cases to be unique.

The solution in Python code

Option 1:

import uuid def generateName(): return str(uuid.uuid4())[:6]
Code language: Python (python)

Option 2:

from random import sample from string import ascii_letters def generateName(length=6): while True: name = ''.join(sample(ascii_letters, length)) if not photoManager.nameExists(name): return name
Code language: Python (python)

Option 3:

generateName=lambda:str(__import__("time").time())[-6:]
Code language: Python (python)

Test cases to validate our solution

for i in range(10): name = generateName(); test.expect(isinstance(name, str), "Name has to be a string."); test.expect(photoManager.nameWasUnique(name), "Name has to be unique."); test.assert_equals(len(name), 6, "Name has to be 6 digits long.");
Code language: Python (python)

See also  How to Convert a Hex String to RGB in Python
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x