-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats.py
More file actions
45 lines (40 loc) · 1.45 KB
/
Copy pathstats.py
File metadata and controls
45 lines (40 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# stats.py
def get_num_words(text):
"""
Accepts text as a string and returns the number of words.
Returns 0 if the input text is None.
"""
if text is None:
return 0
words = text.split()
return len(words)
def get_char_counts(text):
"""
Counts the occurrences of each character in the given text.
Converts all characters to lowercase. Includes symbols and spaces.
Returns a dictionary of {character: count}.
Returns an empty dictionary if the input text is None.
"""
if text is None:
return {}
char_counts_dict = {}
lower_text = text.lower() # Convert text to lowercase
for char in lower_text:
if char in char_counts_dict:
char_counts_dict[char] += 1
else:
char_counts_dict[char] = 1
return char_counts_dict
def sort_char_counts(char_counts_dict):
"""
Takes a dictionary of character counts and returns a sorted list of dictionaries.
Each item in the list is a dictionary like {"char": character, "num": count}.
The list is sorted by count in descending order.
"""
list_of_dicts = []
for char, count in char_counts_dict.items():
list_of_dicts.append({"char": char, "num": count})
# Sort the list of dictionaries by the 'num' key in descending order
# Using sorted() creates a new sorted list
sorted_list = sorted(list_of_dicts, key=lambda item: item["num"], reverse=True)
return sorted_list