Home » Number of Nearest ‘True’ in a matrix or list of list

Number of Nearest ‘True’ in a matrix or list of list

Solutons:


Definitely not the best way to do it, but it’s one that works:

import numpy as np

mas1 = np.array([[True, False,  True],
       [ False,  True,  True],
       [ False,  True,  False]])

mas_answer = np.ndarray(shape=mas1.shape)

for i in range(mas1.shape[0]):
    for j in range(mas1.shape[1]):
        close_elt = []
        if i >= 1:
            try:
                close_elt.append(mas1[i-1,j])
            except:
                pass
            try:
                close_elt.append(mas1[i-1,j+1])
            except:
                pass

        if j >= 1:
            try:
                close_elt.append(mas1[i+1,j-1])
            except:
                pass
            try:
                close_elt.append(mas1[i,j-1])
            except:
                pass

        if i >= 1 and j >= 1:
            try:
                close_elt.append(mas1[i-1,j-1])
            except:
                pass

        try:
            close_elt.append(mas1[i,j+1])
        except:
            pass

        try:
            close_elt.append(mas1[i+1,j])
        except:
            pass
        try:
            close_elt.append(mas1[i+1,j+1])
        except:
            pass

        mas_answer[i,j] = close_elt.count(True)


# Ouput:
mas_answer
Out[27]: 
array([[1., 4., 2.],
       [3., 4., 3.],
       [2., 2., 3.]])

You probably can try this Python approach: (just comment out the print statements)
# filename – my_neighbors.py

from itertools import product

coordinates = list(product(range(3), range(3)))


matrix =  [['A', 'B', 'A'], 
           ['B', 'A', 'A'],
           ['B', 'A', 'B']]

# Number of Nearest 'True' in a matrix or list of list

         #   [[1, 4, 2],
         #    [3, 4, 3],
         #    [2, 2, 3]]


def neighbors(grid, r, c):
    vals = sum((row[c -(c>0): c+2]
                for row in grid[r -(r>0):r+2]), [])
    vals.remove(grid[r][c])      # rm itself.
    return list(vals)            # return all neighbors



new_matrix = [[0 for c in range(3)] for r in range(3)]
#print(new_matrix)

for r, c in coordinates:
    print(f' {r}{c} -> all neighbors: ')
    print(f' t  {neighbors(matrix, r, c)} ')
    neighs = neighbors(matrix, r, c)
    summ   = neighs.count('A')
    print(f' t t summ: {summ} ')
    new_matrix[r][c] = summ


print(new_matrix)

# [[1, 4, 2], [3, 4, 3], [2, 2, 3]]
    

Related Solutions

Java simple accounting program [closed]

There's a spelling mistake (an extra 'e' on the input parameter annualInterest*e*Rate): public void setAnnualInterestRate(double annualInteresteRate){ this.annualInterestRate = annualInterestRate; } Therefore you are setting the this.annualInterestRate to...

pc and mobile site code using user agent

You could do something like this through media queries <link rel="stylesheet" media="screen and (min-device-width: 1024px)" href="https://stackoverflow.com/questions/21937880/pc.css" /> <link rel="stylesheet" media="screen and (max-device-width:...

How many CPU ticks does it take to store a single None? [closed]

In short: In this case, since X does not implement Drop, storing None is done in a single instruction. The number of CPU cycles depends heavily on the exact hardware and on caching effects. But assuming a modern x86-64 CPU and assuming the memory is in L1 cache...

sql aggregate and split [closed]

This uses STRING_AGG to aggregate the strings into one long one, and then a Tally Table to split into the new rows. It is assumed you have a column to order by. if you do not, you cannot achieve what you are after without one as data in a table is stored in an...

What is “-bash: !”: event not found”

You can turn off history substitution using set +H. ! is a special character to bash, it is used to refer to previous commands; eg, !rm will recall and execute the last command that began with the string "rm", and !rm:p will recall but not execute the last...

Visualize a sparse matrix using Python Turtle graphics

What does the problem mean by (rows-1, columns-1)? This is tied up with your mysterious m variable and the order() function you left undefined. Let's proceed anyway. We can see from the matrix() function we're dealing with a square matrix but let's not even...

What does an “extra” semicolon means? [duplicate]

A for loop is often written int i; for (i = 0; i < 6; i++) { ... } Before the first semicolon, there is code that is run once, before the loop starts. By omitting this, you just have nothing happen before the loop starts. Between the semicolons, there is the...

Python: Compare lists, perform operation, create new list

I think the downvotes are justified because you did not provide any code at all to show us what you tried so far, so that we know where you are stuck with your code. Also i think the way you wrote the requirements is a bit confusing (0eth probably means nth...

Python put multiple line array into a single line

I think you did not the best job at describing the problem, it is not really clear why you have such files (i guess most people were assuming you have an existing array in python) containing an array definition as if it was written for a specific language with...

Sort array contains numeric string using c# array

You need give an order (actually a equivalence relation) to be able to sort. The order on characters is usually a,b,c,... and the order usually given on words such as 'one' is called lexicographic order. However you want to sort by the meaning behind, its...

Sort (hex) colors by Hue [closed]

In this updated example also we don't care about hash, we'll just deal with an arrays of hex colors: require 'paint' #intantiate web_colors from gist and shuffle them eval(`curl...

read file string and store in uint8_t array in c [closed]

Is that what you wanted? (to test give binary 01 combination as an first argument) #include <stdio.h> #include <stdint.h> uint8_t charToBin(char c) { switch(c) { case '0': return 0; case '1': return 1; } return 0; } uint8_t CstringToU8(const char *...

my JavaScript using jQuery is not working [closed]

You didn't include jQuery in your code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="https://stackoverflow.com/questions/43397734/temp.js"></script> Make...

How to check if a Date falls in a certain week or Quarter [closed]

I would say do these steps, 1 - figure out first and last day of the week Get current week start and end date in Java - (MONDAY TO SUNDAY) 2 - check if the date falls in between that range or not Java: how do I check if a Date is within a certain range? - if...

How to add two object together

You should use a numeric data type for arithmetic operations (not Object). With out seeing the code in add() my recommendation is to store the total price in a double primitive. double price =0; for(int x = 0; x < rprice.size(); x++) { //you may need to...