Can someone say what went wrong in this code? - python

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

Related

Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K

Problem Statement:- Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K.
**def countpairs(x,length,sum):
count = 0
for i in range(0,length):
for j in range(i+1,length):
print(x[i],x[j])
if(x[i]+x[j]==sum):
count+=1
print(count)
x = [1, 1, 1, 1]
sum = 2
length=len(x)
countpairs(x,length,sum)
Output:= 6**
This is My solution used in VS code.
My Question:- whenever I am running the same code in gfg it is not accepting the code giving me this error. I even have tried the same code in the online compiler there also it is running correctly.
This Is the gfg code which i have written
class Solution:
def getPairsCount(self, arr, K, N):
count = 0
for i in range(0,N):
for j in range(i+1,N):
if(arr[i]+arr[j]==K):
count+=1
return count
#Initial Template for Python 3
if __name__ == '__main__':
tc = int(input())
while tc > 0:
n, k = list(map(int, input().strip().split()))
arr = list(map(int, input().strip().split()))
ob = Solution()
ans = ob.getPairsCount(arr, n, k)
print(ans)
tc -= 1
Error
if(arr[i]+arr[j]==K):
IndexError: list index out of range
There's no added value in using a class for this. You just need:-
def getPairsCount(arr, K):
count = 0
for i in range(len(arr)-1):
if arr[i] + arr[i+1] == K:
count += 1
return count
EDIT:
Previous answer assumed that only adjacent elements were to be considered. If that's not the case then try this:-
import itertools
def getPairsCount(arr, K):
count = 0
for c in itertools.combinations(sorted(arr), 2):
if c[0] + c[1] == K:
count += 1
return count
data = [1, 2, 1, 4, -1]
print(getPairsCount(data, 3))
We do not need two loops for this question. Here is something that runs in O(n):
def countpairs(list_,K):
count = 0
set_ = set(list_)
pairs_ = []
for val in list_:
if K - val in set_:
# we ensure that pairs are unordered by using min and max
pairs_.append ( (min(val, K-val), max(val, K-val)) )
count+=1
set_pairs = set(pairs_)
print ("Pairs which sum up to ",K," are: ", set_pairs)
return len(set_pairs)
x = [1,4,5,8,2,0,24,7,6]
sum_ = 13
print ("Total count of pairs summming up to ", sum_, " = ", countpairs(x, sum_))
Output:
Pairs which sum up to 13 are: {(6, 7), (5, 8)}
Total count of pairs summming up to 13 = 2
The idea is that if two values should sum to a value K, we can iterate through the array and check if there is another element in the array which when paired with the current element, sums up to K. The inner loop in your solution can be replaced with a search using the in. Now, we need this search to be fast (O(1) per element), so we create a set out of our input array (set_ in my example).
def solve(a,K):
freq = {}
for v in a:
if v in freq:
freq[v] += 1
else:
freq[v] = 1
for i in range(len(set(a))):
res += freq[a[i]] * freq[K - a[i]]
return res
a = [int(v) for v in input().split()]
K = int(input())
print(solve(a,K))
# Time Complexity : O(N)
# Space Complexity : O(1)
def solve(a,K):
freq = {}
for v in a:
if v in freq:
freq[v] += 1
else:
freq[v] = 1
for i in range(len(set(a))):
res += freq[a[i]] * freq[K - a[i]]
return res
a = [int(v) for v in input().split()]
K = int(input())
print(solve(a,K))

Why don't I have an output for the sorted merged list and sum(res[i]). I thought the sum function returned the sum of the newly merged array.

I should be printing two values based off my code the newly sorted array and the sum of the newly sorted array. But I keep on getting an error. Why don't I have an output for the sorted merged list and sum(res[i]). I thought the sum function returned the sum of the newly merged array. What does Python mean when it says the int object is not iterable. Can you please explain why the code isn't functioning properly. I apologize for the basic question as I am new to python.
Python program to merge two unsorted lists
# in sorted order
# Function to merge array in sorted order
def sortedMerge(a, b, res, n, m):
# Sorting a[] and b[]
a.sort()
b.sort()
# Merge two sorted arrays into res[]
i, j, k = 0, 0, 0
while (i < n and j < m):
if (a[i] <= b[j]):
res[k] = a[i]
i += 1
k += 1
else:
res[k] = b[j]
j += 1
k += 1
while (i < n): # Merging remaining
# elements of a[] (if any)
res[k] = a[i]
i += 1
k += 1
while (j < m): # Merging remaining
# elements of b[] (if any)
res[k] = b[j]
j += 1
k += 1
# Driver code
a = [ 5, 5, 5, 5 ]
b = [ 100, 100, 100, 100, 100 ]
n = len(a)
m = len(b)
# Final merge list
res = [0 for i in range(n + m)]
sortedMerge(a, b, res, n, m)
print ("Sorted merged list :")
for i in range(n + m):
print (res[i])
print(sum(res[i]))
You could simply achieve this by executing the following code:
def sortandmerge(a,b):
#Returns the sum of the lists
return sum(list(set(a+b)))
If you specifically want the function to return the sorted list too, then
def sortandmerge(a,b):
#Returns the sum of the lists
res = list(set(a+b))
return sum(res), res
And then use the .sort() function where you're receiving the res

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

Convert matrix elements from str to int in Python

I need to convert the elements of a matrix from str to int (after I read them from a file).
I don't want to use any external library.
This is what I produced so far and it's working, but I'm not happy with it (not very pythonic):
def str2int(matrix):
n = 1
m = 1
if type(matrix) is ListType:
n = len(matrix)
if type(matrix[0]) is ListType:
m = len(matrix[0])
new_matrix = []
i = 0
while i < n:
new_matrix.append([])
j = 0
while j < m:
new_matrix[i].append(int(matrix[i][j]))
j += 1
i += 1
return new_matrix
Any better ideas?
Thanks.
Use a list comprehension:
return [[int(i) for i in row] for row in matrix]

Categories

Resources