简体   繁体   中英

finding consecutive numbers in a matrix with python numpy

在此处输入图像描述 I am practicing some exercises and have been going in circles trying to figure it out. The first part is to create a 5x5 matrix with NumPy giving it random values, and I've already solved it.

Now I need to see if the matrix, either horizontally or vertically, has consecutive numbers (for example: The matrix of the attached image does not have consecutive numbers). Here is there are 4 consecutive numbers in the first column: [[50 92 78 84 36] [51 33 94 73 32] [52 94 35 47 9] [53 5 60 55 67] [83 51 56 99 18]]` Here are 4 consecutive numbers in the last row [[50 92 78 84 36] [41 33 94 73 32] [72 94 35 47 9] [55 5 60 55 67] [84 85 86 87 18]]"

The last step is to continue randomizing the array until you find those consecutive numbers.

Here is a naive approach to check whether each row/column of a given matrix has a given amount (4 in this case) of consecutive numbers:


import numpy as np

def has_consecutive_number(M, num_consecutive=4):

    for v in np.vstack((M, M.T)): # You need to check both columns and rows
        count = 1         # Record how many consecutive numbers found
        current_num = 0   # Recording 1 or -1
        for i in range(1, len(v)):
            diff = v[i] - v[i-1]

            if diff == 1:  # if diff is 1
                if current_num != 1: # if previous diff is not 1, reset counter
                    count = 1
                current_num = 1
                count += 1
            elif diff == -1:
                if current_num != -1: count = 1
                current_num = -1
                count += 1
            else: # reset counter
                current_num = 0
                count = 1
            if count == num_consecutive:
                return True
    return False

M1 = np.array([  [10, 43, 74, 32, 69],
                 [20, 19, 69, 83,  8],
                 [89, 31, 62, 61, 17],
                 [35,  3, 77, 22, 29],
                 [52, 59, 86, 55, 73] ])
print(has_consecutive_number(M1, 4))

M2 = np.array([  [10, 43, 74, 32, 69],
                 [20, 19, 69, 83,  8],
                 [89, 31, 62, 61, 17],
                 [35,  3, 77, 22, 29],
                 [52, 53, 54, 55, 73] ])
print(has_consecutive_number(M2, 4))

Output is False for first matrix and True for second matrix

False 
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM