# 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]])

for i in range(mas1.shape):
for j in range(mas1.shape):
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

# Ouput:
Out:
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]]

``````

## Getting last modification date of a PostgreSQL database table

There is no reliable, authorative record of the last modified time of a table. Using the relfilenode is wrong for a lot of reasons: Writes are initially recorded to the write-head log (WAL), then lazily to the heap (the table files). Once the record is in WAL,...

## How do I make this sed script a “one liner”?

An ANSI C string -- with \$'' -- can contain backslash escapes, like \n -- so you can have a newline in sed's arguments while still having the shell command invoking sed be only one line. sed -i \$'/INTERPRETER_PYTHON_DISTRO_MAP/,/version_added/ {\n /default/a\\...

## while loop with break after first iteration is faster than if statement [closed]

iteration while loop: 15ms - if statement is 31ms A comparison of two similar program with runtimes that only differ by 16ms is just a rounding error. It's unclear what optimization flags were used in compiling the program. On those coding competition sites,...

## How to OCR a PDF file and get the text stored within the PDF?

ocrmypdf does a good job and can be used like this: ocrmypdf in.pdf out.pdf To install: pip install ocrmypdf or sudo apt install ocrmypdf # ubuntu sudo dnf -y install ocrmypdf # fedora After learning that Tesseract can now also produce searchable PDFs, I found...

## Keyboard shortcut to access the first link in a Google search page?

Note: As of 2018 the answer is out of date. The triangle arrow next to the search result no longer appears. Assuming you mean the first search result, this is already built in to Google! Notice there is already a little ▶ arrow will next to the first search...

## If …Else If wont work [closed]

First of all, put the javascript code between a <script></script> tag because javascript code will not run in an html <div></div> tag. Then, instead of x == 0||9||2, use x == 0 || x == 9 || x == 2. Kindly indent your code for easier...

## How to convert the object of character to string

Your object of characters is already almost an array. It has numeric indices, but is missing the .length property. If you add that it, it will be an "array like" object, which can then be passed to Array.from to get a proper array. Once you have a real array,...

## How can I write the approximate value of PI?

Because your { and } is wrong. I think brackets will be as given below If the formula is PI = 4/1 - 4/3 + 4/5 - 4/7 + ... ( Leibniz's Series ) then you can formalate as given below #include <iostream> using namespace std; int main() { double n, i; //...

## c# Regex catch string between two string [duplicate]

You can try this: <[a-z\s]+id=[\'\"]mobile[\w]+[\'\"][\sa-zA-Z\d\'\=\;\:]*>([a-zA-Z\d\s]+)<[\/a-z\s]+> Anyway it will not match special chars or symbols. You can test and optimize it here: https://regex101.com/r/fnYQ1o/10 EDIT - Code example This...

## Do I need CSRF token if I’m using Bearer JWT?

This is relevant but doesn't necessarily answer 100% of your question: https://security.stackexchange.com/a/166798/149676 The short of it is that as long as authentication isn't automatic (typically provided by the browser) then you don't have to worry about...

## In python, calculate the differnce in time from a file’s 1st and last line

Once you've retrieved the lines (as you've already done), you can slice out the date, e.g.: >>> "2014-04-28 16:09:51:579491 Computer 0 4"[:26] '2014-04-28 16:09:51:579491' Given that, you can parse it with datetime.strptime. I'll leave you to figure...

## Java cannot find symbol during compiling

The problem is this line: System.out.println(pref); You have not defined pref in this scope. The field pref is only defined in main method but cannot be read outside of it and therefore outside your main method the pref field has to be defined as well. (You may...

## HOW TO MAKE A DYNAMIC PROFILE PAGE? [closed]

Well, for such small tasks no CMS (I mean WP or Drupal) is necessarily needed - customizing one for your needs will me much more painful, than adding a few PHP lines to your HTML files. To make your website able to get data, you will have to make it perform...

## Weird results in c [closed]

In addition to LihOs answer above this block looks wrong: if(tab1[i] != '\0') tab1[i]==result[i]; else if (tab2[i] !='\0') tab2[i]==result[i]; else printf(" "); Don't you mean to assign the value in tab1[i]or tab2[i] to result[i]like this? if(tab1[i] != '\0')...

## convert int (which actually decimal) to string (1234 to “123.4”)

Convert the number to a std::string: char buffer; std::string s = itoa(1234, buffer, 10); Or: std::string s = std::to_string(intNum); Then simply insert() the decimal character into it: s.insert(s.length()-1, "."); Or: s.insert(s.length()-1, 1, '.');...

## Notepad in windows form application [closed]

This should demonstrate how to open Notepad and put text into it. This is a simple example of starting a Notepad process and then adding text to it. Will open a new Notepad.exe process and then add the text "Sending a message, a message from me to you" to the...

## Check whether number is even or odd without using any operator

I think you are talking about no arithmetic operator In this case you can ask yourself, in binary what represents the least significant bit (bit 0)? So you can test that bit to know if a number is odd or even: if (number & 0x01) { // odd number } else { //...

## What is the output of the program with reason?

See annotations: #include <stdio.h> void f(int *p, int *q) // p contains address of i, q contains address of j { p=q; // p now contains address of j *p=2; // assigns 2 to j, not i } int main() { int i=0,j=1; // i contains 0, j contains 1 f( &i, &j...

## Are we forced to create processes that must have the text, data ,heap and stack memory sections? [closed]

Where does the "C program layout = General process layout" association stem from ? ( If we consider all the computer science literature out there...) Each operating system has a method (or methods) of loading programs and starting their execution. This includes...

## Relative imports for the billionth time

Script vs. Module Here's an explanation. The short version is that there is a big difference between directly running a Python file, and importing that file from somewhere else. Just knowing what directory a file is in does not determine what package Python...