Reputation: 53
import numpy as np
import re
def validate(seq):
stl = "".join(np.diff(seq).astype(str))
for x in re.findall("[1]+",stl):
if len(x)>3:
return False
return True
print validate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 20])
print validate([1, 2, 3, 6, 7, 8, 9, 11, 12, 16, 17, 18, 19, 22, 23])
print validate([2, 3, 5, 7, 9, 10, 11, 12, 14, 15, 17, 20, 22, 23, 24])
output
False
True
True
This code check the list and check how many numbers are chained and return False if there are more than 4 together like the first print (1, 2, 3, 4, 5, 6, 7, ...), returning True if there are only 4 in sequence like the second print (6, 7, 8, 9) (16, 17, 18, 19).
So how can I amend the code to return True when the list have only one group with 4 numbers in sequence? Returning False for lists with more than for numbers in sequence?
print validate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 20])
print validate([1, 2, 3, 6, 7, 8, 9, 11, 12, 16, 17, 18, 19, 22, 23])
print validate([2, 3, 5, 7, 9, 10, 11, 12, 14, 15, 17, 20, 22, 23, 24])
output
False
False
True
Upvotes: 0
Views: 133
Reputation: 486
The way you defined validate function is somewhat hard to follow. I rewrote it in the following way
def validate(seq, counts=1, N=4):
if len(seq) < N:
return False
diff_seq = np.diff(seq)
sum_seq = np.array([(np.sum(diff_seq[i:i+N-1])==N-1) for i in range(len(diff_seq)-N+2)])
return np.count_nonzero(sum_seq) == counts
where N
is the length of consecutive numbers in a group and counts
is the number of such groups that you want to have in seq
.
EDIT
You can use convolve to compute sum_seq in function validate
as follows
sum_seq = np.convolve(diff_seq, np.ones((N-1,)), mode='valid') == N-1
This should be much faster and it looks more pythonic.
Upvotes: 0