Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to produce unique folder names from a list of names through a function

I’m trying to create a function in such a way that when I supply a list of folder names to it, it will add _1 to the end of the string to produce a unique folder name if the folder name is not already in the folder_dict.

folder_dict = {}

def get_unique_folder_name(name):
    if name not in folder_dict:
        folder_dict[name] = name
    else:
        folder_dict[name] += '_1'

    return folder_dict[name]


items = [
    'Home_J5',
    'Home_J5',
    'Home_J5',
    'Home_J5_1',
    'Home_J5_1_1',
]

for item in items:
    print(get_unique_folder_name(item))

Current output:

Home_J5
Home_J5_1
Home_J5_1_1
Home_J5_1
Home_J5_1_1

Excepted output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Home_J5
Home_J5_1
Home_J5_1_1
Home_J5_1_1_1
Home_J5_1_1_1_1

>Solution :

I’d restructure the code a little bit:

def get_unique_folder_name(items):
    seen = set()
    for item in items:
        while item in seen:
            item += '_1'
        seen.add(item)
        yield item


items = [
    'Home_J5',
    'Home_J5',
    'Home_J5',
    'Home_J5_1',
    'Home_J5_1_1',
]

for item in get_unique_folder_name(items):
    print(item)

Prints:

Home_J5
Home_J5_1
Home_J5_1_1
Home_J5_1_1_1
Home_J5_1_1_1_1

EDIT: Modified structure (to avoid the global variable):

def get_unique_folder_name():

    seen = set()

    def _inner(item):
        while item in seen:
            item += '_1'
        seen.add(item)
        return item

    return _inner

items = [
    'Home_J5',
    'Home_J5',
    'Home_J5',
    'Home_J5_1',
    'Home_J5_1_1',
]

u = get_unique_folder_name()

for item in items:
    print(u(item))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading