-1

In my code I input some data points and it outputs an array of intervals between the data points: For example, [92 97 97 99 99 99 97 97 98 97 99 98 95]

If there is a value that is 20% less or greater than the mean of the intervals, I want it to print 'Intervals are irregular'. If there is not a value that is 20% less or greater than the mean of the intervals, I want it to print 'intervals are not irregular'.

I calculate the mean of the values in this way:

averageinterval = np.mean(intervals)

Then I tried to write a for loop:

for interval in intervals:
    if interval is 20% > averageinterval:
        print('intervals are irregular')

This gives a syntax error. How can I correctly write this loop?

gmds
  • 19,325
  • 4
  • 32
  • 58
Niam45
  • 552
  • 2
  • 16
  • Could you define what you mean by `mean of the intervals`? – yatu Apr 24 '19 at 10:25
  • so a mean is when you add up all the numbers and then divide by how many numbers there are. The intervals are [92 97 ..... 98 95]. Hence the mean will be 97.23 (2dp) – Niam45 Apr 24 '19 at 10:34

3 Answers3

1

Try this:

def check_regularity(intervals):
    average = intervals.mean()
    regular = all(intervals < average * 1.2) and all(intervals > average * 0.8)
    print(f'The intervals are {"not " * regular}irregular.')

check_regularity(np.array([92, 97, 97, 99, 99, 99, 97, 97, 98, 97, 99, 98, 95]))
check_regularity(np.array([92, 97, 37, 99, 99, 99, 97, 97, 98, 97, 99, 98, 95]))

Output:

The intervals are not irregular.
The intervals are irregular.

If you just want to extract the values that are within that range, then you should do this:

average = intervals.mean()
regular_intervals = intervals[(intervals < average * 1.2) & (intervals > average * 0.8)]
gmds
  • 19,325
  • 4
  • 32
  • 58
0

This is additional information: It seems to me you might be looking for outlier checks. If this is the case: You probalbly want something that tests for deviation of the MEDIAN value, because the mean would be affected too strongly by outliers: I can recommend 1 the answer by Joe Kington.

Arbor Chaos
  • 149
  • 6
-2

There is no such thing as a percentage operator in Python, you will need to define a method that takes the percentage from averageinterval.

Example:

def percentage(part, whole):
  return float(part)/ float(whole) * 100
Fida
  • 1
  • 1