Coverage for src/qollib/strings/numeric.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-02 08:34 +0000

1import re 

2from functools import cmp_to_key 

3 

4NUM_PATTERN = re.compile(r"\d+") 

5 

6 

7def sort_num(strings: list) -> list: 

8 """ 

9 Applies a sorting algorithm to a list of strings containing an integer number. 

10 Selecting the first integer of the string and sort by it (regardless of zero-padded or not) 

11 """ 

12 strings.sort(key=cmp_to_key(num_compare)) 

13 return strings 

14 

15 

16def num_compare(string_a: str, string_b: str) -> int: 

17 start_a = extract_int(string_a) 

18 start_b = extract_int(string_b) 

19 if start_a > start_b: 

20 return 1 

21 if start_a == start_b: 

22 return 0 

23 return -1 

24 

25 

26def extract_int(string: str) -> int: 

27 """ 

28 Extracts an integer from a string with a number. 

29 If multiple numbers, seperated by nun number characters, exist, the first one will be extracted. 

30 """ 

31 matches = NUM_PATTERN.search(string) 

32 if not matches: 

33 return 0 

34 

35 return int(matches.group())