forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomment_density.py
More file actions
109 lines (83 loc) · 4.26 KB
/
comment_density.py
File metadata and controls
109 lines (83 loc) · 4.26 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import os
import sys
def comment_density():
# Path to data_structures directory
data_structures_path = os.path.join(os.path.dirname(__file__), '..', '..', 'data_structures')
if not os.path.exists(data_structures_path):
print(f"Error: data_structures directory not found at {data_structures_path}")
return
total_lines = 0
comment_lines = 0
blank_lines = 0
files_processed = 0
for root, dirs, files in os.walk(data_structures_path):
for file in files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
file_total = len(lines)
file_comments = 0
file_blanks = 0
in_multiline_comment = False
multiline_delimiter = None
for line in lines:
stripped_line = line.strip()
original_line = line
if not stripped_line:
file_blanks += 1
continue
# Check single line comments
if stripped_line.startswith('#'):
file_comments += 1
continue
# Check multi-line comments
line_is_comment = False
temp_line = original_line
while True:
if not in_multiline_comment:
# Look for start of multi-line comment
triple_double_pos = temp_line.find('"""')
triple_single_pos = temp_line.find("'''")
if triple_double_pos != -1 and (triple_single_pos == -1 or triple_double_pos < triple_single_pos):
in_multiline_comment = True
multiline_delimiter = '"""'
line_is_comment = True
temp_line = temp_line[triple_double_pos + 3:]
elif triple_single_pos != -1:
in_multiline_comment = True
multiline_delimiter = "'''"
line_is_comment = True
temp_line = temp_line[triple_single_pos + 3:]
else:
break
else:
line_is_comment = True
end_pos = temp_line.find(multiline_delimiter)
if end_pos != -1:
in_multiline_comment = False
multiline_delimiter = None
temp_line = temp_line[end_pos + 3:]
else:
break
if line_is_comment:
file_comments += 1
total_lines += file_total
comment_lines += file_comments
blank_lines += file_blanks
files_processed += 1
except Exception as e:
continue
code_lines = total_lines - blank_lines - comment_lines
# Calculate comment density
non_blank_lines = total_lines - blank_lines
if non_blank_lines > 0:
comment_density = (comment_lines / non_blank_lines) * 100
else:
comment_density = 0.0
print(f"Code lines: {code_lines}")
print(f"Comment lines: {comment_lines}")
print(f"Comment density: {comment_density:.2f}%")
if __name__ == "__main__":
comment_density()