Help me fix my Halstead Complexity python code. This is my expected output: Distinct…
- User
Help me fix my Halstead Complexity python code.
This is my expected output:
Distinct Operators: 12.0000 Distinct Operands: 7.0000 Total Operators: 27.0000 Total Operands: 15.0000 Vocabulary: 19.0000 Program Length: 42.0000 Calculated Program Length: 62.6670 Volume: 178.4369 Difficulty: 12.8571 Effort: 2292.4400 Time Required to Program: 127.3578 Number of Delivered Bugs: 0.0595
But this is my incorrect output:
Distinct Operators: 4.0000 Distinct Operands: 10.0000 Total Operators: 4.0000 Total Operands: 22.0000 Vocabulary: 14.0000 Program Length: 26.0000 Calculated Program Length: 41.2193 Volume: 98.9912 Difficulty: 4.4000 Effort: 435.5614 Time Required to Program: 24.1979 Number of Delivered Bugs: 0.0330
This is my code:
import re import math from collections import Counter
def halstead_metrics(code): # Define regex patterns for operators and operands in C code operator_pattern = r'\b(main|int|scanf|printf|=|+|-|*|/|%|&|;|,|(|)|{|}|==|!=|<=|>=|<|>|->)\b' operand_pattern = r'\b[a-zA-Z_][a-zA-Z0-9_]\b|\d+|\".?\"|'[^']*''
# Find all operators and operands operators = re.findall(operator_pattern, code) operands = re.findall(operand_pattern, code) # Count occurrences of each operator and operand operator_count = Counter(operators) operand_count = Counter(operands) # Distinct counts of operators and operands distinct_operators = len(operator_count) distinct_operands = len(operand_count) # 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 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 metricsExample 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); } """
- Assistant