#K95392. Group Files by Extension
Group Files by Extension
Group Files by Extension
You are given a list of file names. Each file name contains one or more characters and includes an extension following the last period character .
. Your task is to group the files by their extension (the substring after the last period) in a case-insensitive way, sort each group lexicographically (ignoring case), and print the groups in lexicographical order of their file types (extensions).
For example, if the input file list is ["notes.txt", "photo1.JPG", "photo2.jpg", "document.PDF", "summary.pdf", "archive.zip"]
, then the file type jpg
group should include both "photo1.JPG" and "photo2.jpg" (in sorted order), pdf
should include "document.PDF" and "summary.pdf", and so on.
The main steps are:
- Identify each file's extension as the substring after the last
.
and convert it to lower-case. - Group files by these lower-case extensions.
- Sort the file names within each group lexicographically ignoring case.
- Output each group in a separate line, with the extension followed by a colon and a space separated list of the sorted file names. </p>
Formally, if you denote the set of files as \(F\) and the extension extraction function as \(E(f)\) for file \(f\), then for each unique extension \(e\) (in lower-case), the output should be:
\[ \text{Group}(e) = \{ f \in F \mid E(f)=e \} \]And each such group must be sorted lexicographically using the ordering that ignores case, i.e., for any two file names \(f_1\) and \(f_2\):
\[ \text{if } f_1.lower() < f_2.lower() \text{ then } f_1 \text{ should precede } f_2. \]</p>inputFormat
The first line contains an integer \(n\) (the number of files). The following \(n\) lines each contain a single file name (a non-empty string that includes at least one period .
).
Input is provided from standard input (stdin).
outputFormat
For each unique file extension, print a line in the following format:
ext: file1 file2 ... filek
where ext
is the lower-case file extension and the file names in the group are sorted lexicographically (ignoring case). The groups must be printed in lexicographical order of the extension.
Output should be written to standard output (stdout).
## sample6
notes.txt
photo1.JPG
photo2.jpg
document.PDF
summary.pdf
archive.zip
jpg: photo1.JPG photo2.jpg
pdf: document.PDF summary.pdf
txt: notes.txt
zip: archive.zip
</p>