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

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

``````

## StringBuilder delete methods [closed]

I'd say this is fine. The intent is different. Lets try this for example: String builder sb = new StringBuilder(); sb.append("hello").append("hello"); sb.delete(0,5); sb.toString(); It prints "hello". Had you read the documentation, you'd see that the end is...

## How to concatenate two different values from two different columns with comma ” , ” using TSQL?

if the datatype is numeric types(int,bigint, tinyint,smallint,etc) then you need to cast it to string before you concatenate. if the datatype is string(varchar,char,nvarchar,nchar) then you can directly use concat function select concat(cast(column_1 as...

## How to get specific element from array of type any in swift?

You should not be using JSONSerializer in Swift. A better option is a JSONDecoder. JSONDecoder will allow you to establish and preserve the type information for the data you've decoded. Here is an Playground example of how you would use JSONDecoder to handle...

## Error with resolution operator while referencing model type depending on dynamic variable (PHP 5.2)

I have found the answer here: http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and...

## How to make RecyclerView behave like Paragraph?

The answer is FlexBoxLayoutManager you can use it with RecyclerView put implementation 'com.google.android:flexbox:1.0.0' in your gradle file. Now setting up RecyclerView layout, <?xml version="1.0" encoding="utf-8"?> <RelativeLayout...

## Piping commands after a piped xargs

You are almost there. In your last command, you can use -I to do the ls correctly -I replace-str Replace occurrences of replace-str in the initial-arguments with names read from standard input.  Also, unquoted blanks do not terminate input items; instead the...

## create arrow using css

Try to use Font awsome LINK HTML: <i class="fa fa-arrow-right"></i> fa-arrow-right Yes, there are several ways of doing this. 1. With an image First of all, in order to do what you've suggested, you can indeed use an image - but instead of coloring...

## accessing values structure within structure? [closed]

Just create an object of emp1 inside your main, and give it a value like below and it should be ok emp1 emp; emp.number.number1=3; //printf then with emp.number.number1 😉 You are accessing the value "number1" like emp1.number.number1 but here "emp" data type...

## What’s wrong with this way to add rows to dataframe?

Try: data <- data.frame(A= character(0), B= character(0), stringsAsFactors=FALSE) data[1, ] <- c("AA", "BB") In your example, A and B are factors. I would suggest a different approach from the other answers. If A and B are something like names or ID...

## Panagram python code [closed]

import string def isPanagram(sentence): alphabet = string.lowercase[:26] # list of letters a-z return all(letter in sentence.lower() for letter in alphabet) The function all will return true if all elements in a list are true The list comprehension inside goes...

## Python, using nested lists (list of lists) from user input [closed]

So if I'm understanding correctly, the "Lists of List" comment pertains to nested Lists, The code you have is close to what's needed. I believe this is what you need. print("Enter First name, last name and Student ID number. Then press 0 to continue") userFirst...

## f.getContentPane().add(new hellojava2(” hello, java”)); [closed]

"hello,java" should appear in f frame but it does not. hellojava2 is the program itself. i do not get error message too." If you are not getting any errors, I'm going to assume your program extends JFrame, since the JFrame needs a component to be added and I...

## VB Code explanation? [closed]

Declare a student name variable that we will call studentname as a string. Think of variables as you would do x and y in an algebraic equation. They are simply names for things of a particular type. In a maths equation x and y are numbers. A string is a...

## remove null items from a multidimensional array in C#

Are your null objects always at the end of the multidimentional array? If so use something like this to remove the null items: private static void ReDimMultiObjects(ref object[,] arr, int length) { object[,] arrTemp = new object[length, 3];//New number of...

## The out parameter must be assigned to before control leaves the current method

Your return message variable seems not the be defined when an error occurs in your try-catch block. Simply setting strReturnMssg = string.Empty or a default value at the beginning of your method should suffice. The error is because you haven't assigned a value...

## Check if string contains only one type of letter C# [closed]

Try this: private bool ContainsOnlyOneLetter(string String) { if(String.Length == 0) { return true; } for(int i = 0; i < String.Length;i++) { if(String.Substring(i,1) != String.Substring(0,1)) { return false; } } return true; } And you can use the function...

## Couldn’t understand this SWIFT Fucntion [closed]

You're getting 120 because you're asking the tuple for the sum value twice. The tuple passed back is (min: Int, max: Int, sum: Int). In this case, sum is also index number 2 (min is index zero, max is index one). So in this case statistics.sum == statistics.2...

## Function that takes an input between 0 and 5 and outputs an array of 5 elements that will be used for generating 5 stars in the UI [closed]

For a JavaScript solution, create an array of size 5 for the output. Then loop through every index. If the given number is larger than the current index, output 100. If the number minus the index is between 0 and 1, then output the decimal part times 100. If...

## C++ Cli code stucked [closed]

The code you provided does not work on any numbers. The only thing it does is construct some SQL query check its result During the SQL-query-construction, the code does not assume any "numbers" to be provided. It actually uses a variable called...

## In a remote thread, how do I call functions whose parameters contain pointers? [closed]

The immediate problem in this code is that you're storing pointers to the string parameters in your record. Those pointers are addresses in your main process; they are not valid in the target process. You should store those values in fixed-size arrays in your...