import numpy as np
def flag_anomalies(data, threshold=3, retries=3):
"""
Flags anomalies in a collection of numerical data with retry logic.
Args:
data (list or numpy array): The collection of numerical data.
threshold (float): The number of standard deviations from the mean to consider an anomaly.
retries (int): Number of retry attempts.
Returns:
list: A list of indices where anomalies are detected. Returns an empty list if no anomalies are found after retries.
"""
data = np.array(data) # Convert to numpy array for easier calculations
anomalies = []
for attempt in range(retries):
try:
mean = np.mean(data)
std = np.std(data)
#Identify anomalies
anomalies = np.where(np.abs(data - mean) > threshold * std)[0].tolist()
if anomalies:
break # Exit retry loop if anomalies are found
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt < retries - 1:
# Retry the process
pass # continue to the next attempt
else:
#If all retries failed, return empty list
return []
return anomalies
if __name__ == '__main__':
# Example Usage
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]
anomalies = flag_anomalies(data)
print(f"Anomalies found at indices: {anomalies}")
data2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
anomalies2 = flag_anomalies(data2)
print(f"Anomalies found at indices: {anomalies2}")
data3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1000]
anomalies3 = flag_anomalies(data3, threshold=2, retries=5)
print(f"Anomalies found at indices: {anomalies3}")
Add your comment