Finding value in a matrix using python - python

I am getting the error 'int object is not iterable' on this method in my class. Someone assist me find the bug as I can't see what I am doing wrong
def find(self, val): #finds value in matrix
if 0 <= val <= 8:
for i,j in range(3):
#for j in range(3):
if self.matrix[i][j] == val:
return i, j
return None

def find(self, val): # finds value in matrix
if 0 <= val <= 8:
for i in range(3):
for j in range(3):
if self[i][j] == val:
return i, j
return None
Example:
self = [[2,1,2],[1,6,4],[0,0,2]]
val = 4
i, j = find(self, val)
print(i)
print(j)
Print:
1
2
If define self as matrix of numpy:
def find(self, val): # finds value in matrix
if 0 <= val <= 8:
for i in range(3):
for j in range(3):
if self.item((i, j)) == val:
return i, j
return None

here is the part of your code that is causing the error
for i,j in range(3)
the python's built-in range function generates a sequence of number that are then assigned to one variable, but you're using two variables instead
. This is how your code should be :
def find(self, val): #finds value in matrix
if 0 <= val <= 8:
for i in range(3):
for j in range(3):
if self.matrix[i][j] == val:
return i, j
return None

Related

Name Error: name 'counting sort' is not defined [duplicate]

This question already has answers here:
How can I call a function within a class?
(2 answers)
Closed 2 years ago.
i trying to implement 'Kids With the Greatest Number of Candies'leet'code problem so i started with sorting the array but it gives me this error why?
class Solution:
def counting_sort(arr):
n = len(arr)
k = max(arr) + 1
position = [0] * k
for v in arr:
position[v] += 1
s = 0
for i in range(0, k):
temp = position[i]
position[i] = s
s += temp
result = [None] * n
for v in arr:
result[position[v]] = v
position[v] += 1
return result
def kidsWithCandies(candies, extraCandies):
candies=counting_sort(candies)
main_arr=[True]*len(candies)-1
i=0
biggest=max(candies)
while(candies[i]+extraCandies<biggest and i<len(candies)):
main_arr[i]=False
i+=1
return main_arr
print(kidsWithCandies([2,3,5,1,3],3))
As you're making class of Solution and counting_sort is a method of this class so you can pass self as first parameter (in every class method).
in the end you can make object of class Solution and call method from that object. Your code may look like this.
class Solution:
def counting_sort(self, arr):
n = len(arr)
k = max(arr) + 1
position = [0] * k
for v in arr:
position[v] += 1
s = 0
for i in range(0, k):
temp = position[i]
position[i] = s
s += temp
result = [None] * n
for v in arr:
result[position[v]] = v
position[v] += 1
return result
def kidsWithCandies(self,candies, extraCandies):
candies=self.counting_sort(candies)
main_arr=[True]*len(candies)-1
i=0
biggest=max(candies)
while(candies[i]+extraCandies<biggest and i<len(candies)):
main_arr[i]=False
i+=1
return main_arr
soln = Solution()
print(soln.kidsWithCandies([2,3,5,1,3],3))

Can someone say what went wrong in this code?

I am working on a problem which takes a nums, row, column as parameters and returns a resultant matrix of size row x column.
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
count = 0
i = j = 0
m = [[0]*c]*r
for row in nums:
for val in row:
if j < c and i < r:
print(val,m[i][j], i, j)
m[i][j] = val
print(val,m[i][j], i, j)
count += 1
j += 1
if j == c:
i += 1
j = 0
if count == (r*c):
return m
else:
return nums
When I tested for input like ([[1,2],[3,4]], 4, 1) it generates output [[4],[4],[4],[4]] instead of [[1],[2],[3],[4]]
m = [[0]*c]*r
This creates a list of r references to the same inner list. So, whenever you modify m[0], you're also modifying m[1], and so on, because they're the same list.
You probably wanted something like this:
m = [[0 for _ in range(c)] for _ in range(r)]
[0]*4 gives you four copies of the same object, not four independent lists.
Try
m = [[0 for i in range(c)] for j in range(r)]

Selection sort - python

I can't seem to make my selection sort work. Any idea whats wrong? When run it gives me [5,6,3,1]
Thx!
aList = [1,5,6,3]
def selection_sort( aList):
for i in range(len(aList)):
min = i
j = i + 1
for j in range(len(aList)):
if aList[j] < aList[min]:
min = j
swap(aList, min, i)
print(aList)
def swap(aList, x, y):
temp = aList[x]
aList[x] = aList[y]
aList[y] = temp
selection_sort(aList)
As I mentioned in the comment, it seemed to me that you used j = i + 1 in hopes that it will somehow effect the j in the subsequent loop, but it is a different variable. So is the aList in your function definition, it can have any name, even aList. Your j is iterating over the entire list again and again and hence the min or the smallest value is carried wherever i goes (so it ended up in the end). So what you need to do is make your second loop only iterate through the next items after i.
aList = [1,5,6,3]
def selection_sort(List):
for i in range(len(List)):
min = i
for k in range(i,len(List)):
if List[k] < List[min]:
min = k
swap(List, min, i)
print(List)
def swap(List, x, y):
temp = List[x]
List[x] = List[y]
List[y] = temp
selection_sort(aList)
def select_sort(l):
for i in range(len(l)):
min_loc = i
for j in range(i+1, len(l)):
if l[j] < l[min_loc]:
min_loc = j
l[min_loc],l[i] = l[i], l[min_loc]
return l

Python array slice not working as expected

I'm trying to write a program for a given array and a value, to remove all instances of that value in place and return the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
It should return length = 2, with the first two elements of nums being 2.
Here is my code:
Code 1:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
j = len(nums) - 1
while i <= j:
while i <= j and nums[j] != val:
j -= 1
while i <= j and nums[i] == val:
i += 1
if i <= j:
nums[i], nums[j] = nums[j], nums[i]
return len(nums[i:])
This returns the array slice in reverse order.
Input:
[3,2,2,3]
3
Output: [3,3]
Expected: [2,2]
However, if I make slight modifications at the end of the code 1, it gives me the correct output:
nums[:] = nums[i:]
return len(nums[i:])
Code 2:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
j = len(nums) - 1
while i <= j:
while i <= j and nums[j] != val:
j -= 1
while i <= j and nums[i] == val:
i += 1
if i <= j:
nums[i], nums[j] = nums[j], nums[i]
nums[:] = nums[i:]
return len(nums)
I cant figure out why my code 1 doesnt work. Could someone help me understand why slice doesnt work as expected?
This would do what you intend ("... remove all instances of that value in place and return the new length"):
def remove_element(nums, val):
nums[:] = [x for x in nums if x != val]
return len(nums)
Test:
nums = [3, 2, 2, 3]
val = 3
print(remove_element(nums, val))
print(nums)
Output:
2
[2, 2]
Your first example works.
When you slice a new list is created. So in your first code sample you are creating a new list at the end containing the correct result, but never returning it.
In your second code example you are assigning the newly created list to the original list and are hence able to access the final result.

IndexError: list index out of range using classes

class Island (object):
def __init__(self, i,j,k, wolf_count=0, eagle_count=0, rabbit_count=0, pigeon_count=0,):
'''Initialize grid to all 0's, then fill with animals
'''
# print(n,prey_count,predator_count)
self.i=i
self.j=j
self.k=k
self.cube= []
for k in range(k):
self.square=[]
for j in range(j):
row=[0]*i
self.square.append(row)
self.cube.append(self.square)
self.init_animals(wolf_count, eagle_count, rabbit_count, pigeon_count)
def init_animals(self,wolf_count, eagle_count, rabbit_count, pigeon_count):
count = 0
while count < wolf_count:
i = random.randint(0,self.i-1)
j = random.randint(0,self.j-1)
k = 0
if not self.animal(i,j,k):
new_Wolf=Wolf(island=self,i=i,j=j,k=0)
count += 1
self.register(new_Wolf)
def animal(self,i,j,k):
'''Return animal at location (i,j,k)'''
if 0 <= i < self.i and 0 <= j < self.j and 0 <= k < self.k:
return self.cube[i][j][k]
else:
return -1
These are sections of my program which are calling each other. When I try to run the program it gives me:
IndexError: list index out of range.
It says it for the return self.cube[i][j][k] in animal(). In reference to the if not self.animal(i,j,k): section in init_animals(). which is again in reference to the line isle = Island(i,j,k, initial_Wolf, initial_Pigeon, initial_Eagle, initial_Rabbit) in __init__().
any idea why I get this error? Sorry if its hard to read.
Your outer list self.cube has k entries, each a nested list with j entries, each containing lists of i entries. Reverse your indices:
return self.cube[k][j][i]
or invert the way you are creating your self.cube list:
for _ in range(i):
square = []
for _ in range(j):
square.append([0] * k)
self.cube.append(self.square)
or more compact still using list comprehensions:
self.cube = [[[0] * k for _ in range(j)] for _ in range(i)]

Categories

Resources