To debug the Python code you've provided for calculating Halstead complexity metrics, we need to ensure that the identification and counting of operators and operands are done correctly. Based on your requirements, it seems like the operator detection regex is missing some crucial elements, and so is the operand detection.
Let’s address the issues by modifying the code. Here’s an updated version of your halstead_metrics function with comments explaining the changes:
import re
import math
from collections import Counter
def halstead_metrics(code):
# Define regex patterns for operators and operands
operator_pattern = r'\bmain\b|\(|\)|\{|\}|\bint\b|\bscanf\b|&|=|\+|\/|\bprintf\b|,|;'
operand_pattern = r'\b[a-zA-Z_][a-zA-Z0-9_]*\b|\"[^\"]*\"|\b\d+\b'
# Find all operators and operands
operators = re.findall(operator_pattern, code)
operands = re.findall(operand_pattern, code)
# Print debug outputs
print("Operators found (raw):", operators)
print("Operands found (raw):", operands)
# Remove duplicates by converting to sets
unique_operators = set(operators)
unique_operators = {item for item in unique_operators if item}
unique_operands = set(operands)
# Ensure operands do not contain any operators
final_operands = unique_operands - unique_operators
# Convert back to lists
unique_operators = list(unique_operators)
unique_operands = list(final_operands)
# Count occurrences of each operator and operand
operator_count = Counter(operators)
operand_count = Counter(operands)
# Print operator and operand counts for debugging
print("\nOperator counts:")
for op, count in operator_count.items():
print(f"{op}: {count}")
print("\nOperand counts:")
for opd, count in operand_count.items():
print(f"{opd}: {count}")
# Distinct counts of operators and operands
distinct_operators = len(unique_operators)
distinct_operands = len(unique_operands)
# Total counts of operators and operands
total_operators = sum(operator_count.values())
total_operands = sum(operand_count.values())
# Calculate Halstead metrics
vocabulary = distinct_operators + distinct_operands
program_length = total_operators + total_operands
# Calculated Estimated Program Length (N')
calculated_length = (
(distinct_operators * math.log2(distinct_operators) if distinct_operators > 0 else 0) +
(distinct_operands * math.log2(distinct_operands) if distinct_operands > 0 else 0)
)
# Volume (V)
volume = program_length * math.log2(vocabulary) if vocabulary > 0 else 0
# Difficulty (D)
difficulty = (distinct_operators / 2) * (total_operands / distinct_operands) if distinct_operands > 0 else 0
# Effort (E)
effort = difficulty * volume
# Time Required to Program (T)
time_required = effort / 18
# Number of Delivered Bugs (B)
bugs = volume / 3000
# Return metrics in a dictionary
metrics = {
"Distinct Operators": distinct_operators,
"Distinct Operands": distinct_operands,
"Total Operators": total_operators,
"Total Operands": total_operands,
"Vocabulary": vocabulary,
"Program Length": program_length,
"Calculated Program Length": calculated_length,
"Volume": volume,
"Difficulty": difficulty,
"Effort": effort,
"Time Required to Program": time_required,
"Number of Delivered Bugs": bugs
}
return metrics
# Example usage
if __name__ == "__main__":
code_sample = """
main()
{
int a, b, c, avg;
scanf("%d %d %d", &a, &b, &c);
avg = (a + b + c) / 3;
printf("avg = %d", avg);
}
"""
metrics_result = halstead_metrics(code_sample)
for metric, value in metrics_result.items():
print(f"{metric}: {value:.4f}")
Important Changes and Additions:
- Operator Pattern: Adjusted
operator_pattern to correctly capture ( and ) as single operators instead of $$.
- Operand Filtering: Removed the extra filtering when collecting operands to ensure that distinct operands are considered without excluding valid ones.
- Raw Output: Added debug statements to print raw operators and operands. This will help you see what is being captured before counting them.
- Operator Counts: Simplified how the counts are collated.
Running the Code:
The code should produce the correct counts now, based on your expectations. Make sure to run this modified code with your sample input. After running it, verify both the distinct counts and the total counts align with your provided expected results.