Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to make file names unique using Python
When creating multiple files or directories with the same name, file systems automatically add suffixes to make each name unique. This problem simulates that behavior by adding (k) suffixes where k is the smallest positive integer that keeps the name unique.
So, if the input is like names = ["my_dir","my_dir(1)","my_new_dir","my_new_dir","abc"], then the output will be ['my_dir', 'my_dir(1)', 'my_new_dir', 'my_new_dir(1)', 'abc'] because "my_new_dir" appears twice, so the second occurrence gets suffix "(1)".
Algorithm
To solve this, we will follow these steps ?
Create a dictionary to track name occurrences
Create a result list to store unique names
-
For each name in the input:
If name hasn't been seen before, add it directly
If name exists, generate a new name with suffix (k) where k ensures uniqueness
Update the dictionary and add the unique name to results
Implementation
from collections import defaultdict
def solve(names):
dic = defaultdict(int)
res = []
for name in names:
if name not in dic:
dic[name] += 1
res.append(name)
else:
newname = name + '(' + str(dic[name]) + ')'
while newname in dic:
dic[name] += 1
newname = name + '(' + str(dic[name]) + ')'
dic[newname] = 1
res.append(newname)
return res
# Test the function
names = ["my_dir", "my_dir(1)", "my_new_dir", "my_new_dir", "abc"]
result = solve(names)
print("Input:", names)
print("Output:", result)
Input: ['my_dir', 'my_dir(1)', 'my_new_dir', 'my_new_dir', 'abc'] Output: ['my_dir', 'my_dir(1)', 'my_new_dir', 'my_new_dir(1)', 'abc']
How It Works
The algorithm uses a defaultdict to track how many times each base name has been encountered:
"my_dir" ? First occurrence, added directly
"my_dir(1)" ? First occurrence, added directly
"my_new_dir" ? First occurrence, added directly
"my_new_dir" ? Second occurrence, becomes "my_new_dir(1)"
"abc" ? First occurrence, added directly
Example with More Duplicates
# Test with more complex duplicates
names = ["file", "file", "file", "file(1)", "file"]
result = solve(names)
print("Input:", names)
print("Output:", result)
Input: ['file', 'file', 'file', 'file(1)', 'file'] Output: ['file', 'file(1)', 'file(2)', 'file(1)', 'file(3)']
Conclusion
This solution efficiently handles file name conflicts by tracking occurrences and generating unique suffixes. The algorithm ensures that each generated name is unique by checking against all previously created names in the dictionary.
