Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Named groups are used. I think it sorts right not only that weak test. solution in Clear category for Sort by Extension by filonich.v
from typing import List
import re
def sort_by_ext(files: List[str]) -> List[str]:
"""
Look for pattern of a file that has extension.
If fail then the extension is empty and name = file.
Ii is mportant to consider that 'name' < 'name.', '.' < 'a'.
"""
def key(file: str):
m = re.search('(?P.+)\.(?P.*)', file)
if m is not None and m.group('ext') != '':
name, ext = m.group('name'), m.group('ext')
else:
name, ext = file, ''
return ext, file
return sorted(files, key=key)
if __name__ == '__main__':
print("Example:")
print(sort_by_ext(['1.cad', '1.bat', '1.aa']))
# These "asserts" are used for self-checking and not for an auto-testing
assert sort_by_ext(['1.cad', '1.bat', '1.aa']) == ['1.aa', '1.bat', '1.cad']
assert sort_by_ext(['.config', 'config', 'name.', 'name', 'no.name', 'abc', 'a']) == ['.config', 'a', 'abc', 'config', 'name', 'name.', 'no.name']
assert sort_by_ext(['1.cad', '1.bat', '1.aa', '2.bat']) == ['1.aa', '1.bat', '2.bat', '1.cad']
assert sort_by_ext(['1.cad', '1.bat', '1.aa', '.bat']) == ['.bat', '1.aa', '1.bat', '1.cad']
assert sort_by_ext(['1.cad', '1.bat', '.aa', '.bat']) == ['.aa', '.bat', '1.bat', '1.cad']
assert sort_by_ext(['1.cad', '1.', '1.aa']) == ['1.', '1.aa', '1.cad']
assert sort_by_ext(['1.cad', '1.bat', '1.aa', '1.aa.doc']) == ['1.aa', '1.bat', '1.cad', '1.aa.doc']
assert sort_by_ext(['1.cad', '1.bat', '1.aa', '.aa.doc']) == ['1.aa', '1.bat', '1.cad', '.aa.doc']
print("Coding complete? Click 'Check' to earn cool rewards!")
Oct. 27, 2020