Skip to content

Commit 51304b5

Browse files
GCI106 AvoidSqrtInLoop add Python tests
Co-authored-by: DataLabGroupe-CreditAgricole <[email protected]>
1 parent 7c2a701 commit 51304b5

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

src/test/resources/checks/avoidSqrtInLoop.py

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,43 @@
11
import math
22
import 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+
441
def 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

2764
def 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

3369
def 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

3873
def 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

Comments
 (0)