Getting interior elements of a 2D array only - python

I have a matrix like the below:
test_numpy_array = np.array([[2,3,4,5],
[6,4,1,2],
[3,4,5,1],
[8,9,7,6],
[4,1,2,5]])
How do I extract only the interior numbers, such that they have 8 neighbors for an array of any size?

This should work:
test_numpy_array[1:-1, 1:-1]

If you're looking for help regarding determination of whether each element is a local minimum, you should probably edit your original post to reflect that.
Regardless, here's some code to push you in the right direction for that. Not sure if you wanted to print, or get a 2D boolean area or what, but this should get you close enough.
def is_local_min(a, r, c):
for i in range(r-1, r+2):
for j in range(c-1, c+2):
if i == r and j == c:
continue
if a[i][j] < a[r][c]:
return False
return True
def get_local_mins(arr):
local_mins = []
for i in range(1, np.shape(arr)[0]-1):
for j in range(1, np.shape(arr)[1]-1):
if is_local_min(arr, i, j):
local_mins.append((i, j))
return local_mins

Related

Pattern printing with arrays/tuples

So I'm trying to do this
You will be given a positive integer n > 0 and you will construct a pattern that is made up of n rows:
• Row 0 contains 1 number—the number 1
• Each row is one longer than the one before and follows the pattern that ensues
So if variable n:int = 4, the output would be
[1]
[1,2]
[2,3,5]
[5,7,10,15]
The number in the current array is added to the number immediately above it in the previous array and appended at the end of the current array. Also when starting a new array the last element of the previous array is considered as the first element of the current array.
I apologize if my question is unclear, but I hope after the example and explanation I provided, the question is clearer now.
Here is my code:
def append(n: int):
for x in range(1,n+1):
return(x,x+1)
print(append(n))
When I put n = 4, it doesnt seem to work, what's the problem here?
This will do it:
def func(n):
mylist = []
for i in range(n):
if i == 0:
mylist.append([1])
else:
mylist.append(createnewlist(mylist[i-1]))
return mylist
def createnewlist(a):
newlist = []
for i in range(len(a)+1):
if i == 0:
newlist.append(a[len(a)-1])
else:
value = a[len(a)-1]
for m in range(i):
value += a[m]
newlist.append(value)
return newlist
print(func(6))
I don't think your code will return the pattern you want to show. Here's a little code I wrote to print that pattern but there are two loops running, if you could optimize that you could do it or else use the code just as it is.
n=4
arr=[1]
brr = [1]
print(brr)
for i in range(0,n-1):
brr = arr[i:]
for k in range(0,len(arr)):
brr.append(arr[k]+brr[k])
arr = brr
print(brr)

Check array to find if they are the same

I am new to programming in Python. I had used Matlab extensively. I want to check if in a 2D array,any two arrays are same. I have points lets say (x,y,z) coordinates in the format
data=[[x1,y1,z1],[x2,y2,z2]...[xn,yn,zn]].
I want to check if any point is equal to another point. And if there are any similar instance, i want to know how many are same and which two are same. The code i have in Python is something like
data = [[1,2,3],[3,1,8],[4,2,5],[1,2,3]]
s=0
for i in range(len(data)):
a=data[i]
for j in range(len(data)):
while i != j:
if data[j]==a:
s=s+1
c=i
d=j
print(s)
print(c,d)
and i also dont want the answer that point N is equal to point N etc
I also have used
for j in range(i,len(R)):
but it also dont give the correct answer.
This working well:
data =[[1,2,3],[4,5,6],[2,5,6],[0,9,1],[1,5,7],[2,5,4]]
st=[]
dic={}
while len(data)>1:
d = data[0]
data.remove(d)
st=[]
for dat in data:
k=0
for i in d:
if i in dat:
k=k+1
if k>1:
st.append(dat)
if len(st)>0:
dic[str(d)]=st
for key in dic.keys():
print(key," : ", dic[key])
Apparently, found a workthrough myself
d=[[1,2,3],[3,5,4],[5,6,9],[0,2,1],[1,2,3]]
s=0
for i in range(len(d)):
for j in range(i+1,len(d)):
if d[i]==d[j]:
s=s+1
x=i
y=j
print(s)
print(x,y)

2d Array Python :list index out of range

I am new to Python programming and I am trying to write code to check if a DFA( Deterministic Finite Automata) has empty language or not.
I am using 2-d array to store state of the DFA.
On executing the code I keep getting list index out of range. How can I fix this?
Below is the code
top=-1
count=0
n=int(input("\nEnter the no of states"))
mat=[[]]
b=[]
print("\nEnter the transition table")
for i in range(0,n):
for j in range(0,n):
mat.append(input())
finalState=input("\nEnter the final state:")
startState=input("\nEnter the start state:")
for i in range(0,n):
for j in range(0,n):
if mat[i][j]:
b[++top]=j
for k in range(top):
if b[k]==finalState:
count+=1
if count>0:
print("\nLanguage is not empty")
else:
print("\nLanguage is empty")
when you make a 2x2 table, you want mat to be [[1,2],[3,4]], but you're getting [[],1,2,3,4] right now.
Instead, try:
mat = []
for i in range(n):
row = []
for j in range(n):
row.append(input())
mat.append(row)
Also, Python does not have a "++" operator, so b[++top]=j is the same as b[top] = j. If you want to increment top, you have to do that on its own line before you use it to index the list.
On top of that, b has zero elements, so indexing it in any way will cause a crash. If you're trying to increase the size of b by adding new items to it, use append. Then you don't need a top variable at all.
b.append(j)

Having problems with code I wrote to get inverse of a matrix for each nonzero element and 0 to 0

I am totally new to programming, and I have written this function function to take a matrix and maps each nonzero element to its inverse and zero to zero in python. Here is my code:
def question_1_c(arr):
new_arr = []
for i in range(len(arr)):
row_arr = []
for j in range(len(arr[i])):
row_arr.append(1/ arr[i][j])
new_arr.append(row_arr)
return new_arr
question_1_c([[70,0,13,67],[90,48,57,26],[43,45,67,89],[88,65,44,23]])
For some reason it gives an error. Can anyone help?
The error that I got was a divide by zero, which makes sense because you're never checking for zero values. You're also doing integer division - which will not do what you expect it to do.
Also, in Python you can iterate over collections. I've rewritten your code, and this should do what you expect it to do.
def question_1_c(arr):
new_arr = []
for row in arr:
row_arr = []
for val in row:
if val:
row_arr.append(1.0/val)
else:
row_arr.append(val)
new_arr.append(row_arr)
return new_arr
the array has a 0 value, in [0,1] position... so in
1/ arr[i][j] the program do:
1/0, and that throw an exception.
You must consider this case do somethig like this:
if arr[i][j]==0:
...
else:
row_arr.append(1/ arr[i][j])

output repetition

I wrote this program which outputs pythagorean triplet whose sum is a certain number(this would be the parameter). The program runs perfectly but the same triplet is appearing multiple times and I want one triplet to appear just once. I was wondering if someone could help me out. Thanks!
def pythagoreanCheck(tripletList):
'''
Checks whether the three numbers are pythagorean triplet
returns True or False
'''
trip_list = [0,1,2]
if tripletList[0]**2 + tripletList[1]**2 == tripletList[2]**2:
return True
else:
return False
def givMeSum(target):
'''
returns 3 numbers such that their sum is equal to target
'''
listOfa = xrange(1,target)
listOfb = xrange(1,target)
listOfc = xrange(1,target)
for i in listOfa:
for j in listOfb:
for k in listOfc:
add = i + j + k
if add == target:
add_list = [i,j,k]
add_list.sort()
value = pythagoreanCheck(add_list)
if value:
print add_list
def main():
givMeSum(12)
main()
It's because you're doing your calculations in a nested list and then creating a sorted list of 3 different permutations of the same numbers.
Since i, j, and k will enter different combinations of the same three numbers 3 times, add will equal target each time, which means that add_list is created and sorted 3 times. Which means that it will create the same list 3 times.
I think that you should just take out
add_list.sort()
And Siddharth is right, your algorithm is really inefficient. You're turning it into an O(n^3) algorithm, which could take a really long time with larger target numbers.
Consider storing each tuple in a hash table (dictionary)instead of printing it within the innermost loop. At the end of all the loops completion, print all the values in the hash.
Aside from your question, you can make the algo faster by creating a hash of integers and replace the innermost loop with a hash search.
You need to make sure that i <= j <= k:
def pythagoreanCheck(tripletList):
'''
Checks whether the three numbers are pythagorean triplet
returns True or False
'''
a, b, c = tripletList
return a**2 + b**2 == c**2
def givMeSum(target):
'''
returns 3 numbers such that their sum is equal to target
'''
for i in xrange(1, target):
for j in xrange(i, target): # j >= i
for k in xrange(j, target): # k >= j
if i + j + k == target:
add_list = [i, j, k] # no need to sort any more
if pythagoreanCheck(add_list):
print add_list
def main():
givMeSum(12)
main()
As noted, this algorithm is far from optimal, but this will at least solve the problem you're seeing.
Here's a slightly better way (two nested loops instead of three):
def giveMeSum(target):
'''
returns 3 numbers such that their sum is equal to target
'''
for i in xrange(1, target):
for j in xrange(i, target):
k = target - i - j
if k < j:
break # skip to the next value of i - all remaining js are too big
add_list = [i, j, k]
if pythagoreanCheck(add_list):
print add_list

Categories