fork download
  1. import re
  2.  
  3. re_natural = re.compile('[0-9]+|[^0-9]+')
  4.  
  5. def natural_key2(s):
  6. parts = re_natural.findall(s)
  7. natural = [(1, int(c)) if c.isdigit() else (0, c.lower()) for c in parts]
  8. ties_alpha = [c for c in parts if not c.isdigit()]
  9. ties_numeric = [c for c in parts if c.isdigit()]
  10. return natural + [(-1,)] + ties_alpha + ties_numeric
  11.  
  12. test_cases = [
  13. # (unsorted list, sorted list)
  14. (list('bca'), ['a', 'b', 'c']),
  15. (list('CbA'), ['A', 'b', 'C']),
  16. (list('r0B9a'), ['a', 'B', 'r', '0', '9']),
  17. (['a2', '1a', '10a', 'a1', 'a100'], ['a1', 'a2', 'a100', '1a', '10a']),
  18. (['GAM', 'alp2', 'ALP11', '1', 'alp100', 'alp10', '100', 'alp1', '2'],
  19. ['alp1', 'alp2', 'alp10', 'ALP11', 'alp100', 'GAM', '1', '2', '100']),
  20. (list('ra0b9A'), ['A', 'a', 'b', 'r', '0', '9']),
  21. (['Abc', 'abc', 'ABc'], ['ABc', 'Abc', 'abc']),
  22. (['0A', '00a', 'a', 'A', 'A0', '00A', '0', 'a0', '00', '0a'],
  23. ['A', 'a', 'A0', 'a0', '0', '00', '0A', '00A', '0a', '00a'])
  24. ]
  25.  
  26. for case in test_cases:
  27. print(case[1])
  28. print(sorted(case[0], key=natural_key2))
  29.  
Success #stdin #stdout 0.02s 5760KB
stdin
Standard input is empty
stdout
['a', 'b', 'c']
['a', 'b', 'c']
['A', 'b', 'C']
['A', 'b', 'C']
['a', 'B', 'r', '0', '9']
['a', 'B', 'r', '0', '9']
['a1', 'a2', 'a100', '1a', '10a']
['a1', 'a2', 'a100', '1a', '10a']
['alp1', 'alp2', 'alp10', 'ALP11', 'alp100', 'GAM', '1', '2', '100']
['alp1', 'alp2', 'alp10', 'ALP11', 'alp100', 'GAM', '1', '2', '100']
['A', 'a', 'b', 'r', '0', '9']
['A', 'a', 'b', 'r', '0', '9']
['ABc', 'Abc', 'abc']
['ABc', 'Abc', 'abc']
['A', 'a', 'A0', 'a0', '0', '00', '0A', '00A', '0a', '00a']
['A', 'a', 'A0', 'a0', '0', '00', '0A', '00A', '0a', '00a']