Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/python/comprehensions.txt

1.5 KiB, 1 run

created by r1870400018:12026, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1from collections import Counter
2from typing import Dict, List, Set
3
4
5def word_lengths(words: List[str]) -> Dict[str, int]:
6 return {w: len(w) for w in words}
7
8
9def unique_chars(text: str) -> Set[str]:
10 return {c.lower() for c in text if c.isalpha()}
11
12
13def flatten(nested: List[List]) -> List:
14 return [item for sublist in nested for item in sublist]
15
16
17def matrix_transpose(matrix: List[List[float]]) -> List[List[float]]:
18 if not matrix:
19 return []
20 return [[row[i] for row in matrix] for i in range(len(matrix[0]))]
21
22
23def group_by_length(words: List[str]) -> Dict[int, List[str]]:
24 result: Dict[int, List[str]] = {}
25 for word in words:
26 length = len(word)
27 if length not in result:
28 result[length] = []
29 result[length].append(word)
30 return result
31
32
33def top_n_words(text: str, n: int = 10) -> List[tuple]:
34 words = text.lower().split()
35 cleaned = [''.join(c for c in w if c.isalnum()) for w in words]
36 counts = Counter(w for w in cleaned if w)
37 return counts.most_common(n)
38
39
40def chunk(lst: List, size: int) -> List[List]:
41 return [lst[i:i + size] for i in range(0, len(lst), size)]
42
43
44if __name__ == '__main__':
45 text = "the quick brown fox jumps over the lazy dog the fox"
46 print(f"unique chars: {sorted(unique_chars(text))}")
47 print(f"top words: {top_n_words(text, 3)}")
48
49 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
50 print(f"transpose: {matrix_transpose(matrix)}")
51 print(f"chunks: {chunk(list(range(10)), 3)}")