Coverage for src/qollib/strings/numeric.py: 100%
19 statements
« prev ^ index » next coverage.py v7.5.4, created at 2024-06-24 08:41 +0000
« prev ^ index » next coverage.py v7.5.4, created at 2024-06-24 08:41 +0000
1import re
2from functools import cmp_to_key
4NUM_PATTERN = re.compile(r"\d+")
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
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
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
35 return int(matches.group())