11import math
22import numpy as np
33
4+ results = []
5+ numbers = [1 , 2 , 3 , 4 , 5 ]
6+ for n in numbers :
7+ results .append (math .sqrt (n )) # Noncompliant {{Avoid using scalar sqrt functions in loops. Apply vectorized sqrt operations on arrays directly.}}
8+
9+ results = []
10+ for x in [9 , 16 , 25 ]:
11+ results .append (np .sqrt (x )) # Noncompliant {{Avoid using scalar sqrt functions in loops. Apply vectorized sqrt operations on arrays directly.}}
12+
13+ results = []
14+ i = 0
15+ while i < 3 :
16+ results .append (np .sqrt (i )) # Noncompliant {{Avoid using scalar sqrt functions in loops. Apply vectorized sqrt operations on arrays directly.}}
17+ i += 1
18+
19+ results = []
20+ for n in range (10 ):
21+ val = math .sqrt (n ) # Noncompliant {{Avoid using scalar sqrt functions in loops. Apply vectorized sqrt operations on arrays directly.}}
22+ results .append (val )
23+
24+ class DataProcessor :
25+ numbers = np .array ([1 , 4 , 9 ])
26+ sqrt_values = np .sqrt (numbers )
27+
28+ x = math .sqrt (25 )
29+
30+ class Analyzer :
31+ def __init__ (self , data ):
32+ self .results = np .sqrt (np .array (data ))
33+
34+ intermediate = []
35+ for n in range (3 ):
36+ intermediate .append (n )
37+ final = np .sqrt (np .array (intermediate ))
38+
39+ results = np .sqrt ([x for x in range (5 )])
40+
441def non_compliant_math_sqrt_in_for_loop ():
542 numbers = [1 , 2 , 3 , 4 , 5 ]
643 results = []
@@ -26,16 +63,13 @@ def non_compliant_math_sqrt_in_while_loop():
2663
2764def compliant_numpy_vectorized_sqrt ():
2865 numbers = np .array ([1 , 2 , 3 , 4 , 5 ])
29- # Vectorized sqrt directly on the array - efficient
3066 results = np .sqrt (numbers )
3167 return results
3268
3369def compliant_list_comprehension_with_vectorized_operation ():
3470 numbers = [1 , 2 , 3 , 4 , 5 ]
35- # Using numpy's vectorized sqrt on the entire array at once
3671 return np .sqrt (np .array (numbers ))
3772
3873def compliant_math_sqrt_outside_loop ():
39- # Using math.sqrt outside of a loop is OK
4074 value = 16
4175 return math .sqrt (value )
0 commit comments