Hackerrank day 11 error on webpage but not on spyder - python-3.x

recently I made this code here for the Day 11 of Hackerrank 30 day coding challenge:
arr = [[1,1,1,0,0,0],[0,1,0,0,0,0],[1,1,1,0,0,0],[0,0,2,4,4,0],[0,0,0,2,0,0],[0,0,1,2,4,0]]
f=0
sumas = []
while f<(len(arr)-2):
c = 0
for i in range(len(arr) - 2):
sumas.append((sum(arr[0+f][c:3+c]) + arr[1+f][1+c] + sum(arr[2+f][c:3+c])))
c+=1
f+=1
print(max(sumas))
It takes subarrays from "arr" and sum all the integers on it after that takes the maximum sum number from the subarrays.
When I run my code on spyder works fine but I am getting this error here while running on Hackerrank;
Error (stderr)
Traceback (most recent call last):
File "Solution.py", line 10, in <module>
print(max(sumas))
ValueError: max() arg is an empty sequence
Hope anyone can help me.

the elements in the "I" shape follows this pattern
arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
so we can traverse through the complete array with this
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
ans=[]
for i in range(4):
for j in range(4):
su=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
ans.append(su)
print(max(ans))

Related

Python: Function Error TypeError: tuple indices must be integers or slices, not tuple & TypeError: 'int' object is not subscriptable

Have been applying below code on my function, but regularly getting an error. Please can you explain where am i going wrong
clusters = np.zeros((len(dataset),1))
def assign(centroids,dataset,clusters,k):
numOfObject=len(dataset)
#for every object in the dataset
for i in range(numOfObject):
X=dataset[i,1:-1]
#find the closest centroid
centroidOfX= -1
distanceToClosestcentroids = np.Inf
for y in range(k):
currentcentroids=centroids[y,:]
dist=distance(X,currentcentroids)
if dist<distanceToClosestcentroids:
#Found closer Centroid
distanceToClosestcentroids= dist
centroidOfX=y
#assign to X its closest centroid
clusters[i]=int(centroidOfX)
#assign((2.5),dataset,clusters,20)
assign((2,1),dataset,clusters,20)
Dont really know why i am prompted with this error
Traceback (most recent call last):
File "c:\library\K-Mean.py", line 71, in <module>
assign((2.5),dataset,clusters,20)
File "c:\library\K-Mean.py", line 62, in assign
currentcentroids=centroids[y,:]
TypeError: 'float' object is not subscriptable
PS C:\library> & "C:/Users/ASHISH SHARMA/AppData/Local/Microsoft/WindowsApps/python3.9.exe" c:/library/K-Mean.py
Traceback (most recent call last):
File "c:\library\K-Mean.py", line 71, in <module>
assign((2,1),dataset,clusters,20)
File "c:\library\K-Mean.py", line 62, in assign
currentcentroids=centroids[y,:]
TypeError: tuple indices must be integers or slices, not tuple
The code worked perfectly, the values entered was not in right order
def assign(centroids, dataset, clusters,k):
"""The Assign Function helps overall assigning the value to the functions used in the K-Means and K-Medians
Args:
centroids (NDArray(Float64)): This helps us store the value for the centroid of the cluster
dataset (NDArray): Dataset which we are using in the program to calculate K-Means and K-Medians
clusters (NDArray(Float64)): The different clusters formed by the program to classify them into different categories
k (int): The number of times we have to iterate the function
"""
numOfObjects = len(dataset)
#for every object in the dataset
for i in range(numOfObjects):
X = dataset[i, 1:-1]
#find the closest centroid
centroidsOfX = -1
distanceToClosestcentroids = np.Inf
for y in range(k):
currentcentroids = centroids[y,:]
dist = distance(X, currentcentroids)
if dist < distanceToClosestcentroids:
#Finally found closer Centroid
distanceToClosestcentroids = dist
centroidsOfX = y
#Assign to X its closest centroid
clusters[i] = int(centroidsOfX)

I am trying to make a prime number generator in Python3 and the input function is not working properly [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
There is probably a simple answer to this, but I'm new and have no idea what I'm doing as I am learning everything from google and reddit.
My code is:
def primefinder(z):
primenumber_list=[]
for y in range(2, z+1):
if y not in primenumber_list:
print(y)
for x in range(y*y,z+1,y):
primenumber_list.append(x)
q=input('Enter maximum:')
print(primefinder(q))
The error is like this:
Traceback (most recent call last):
File "primenumber.py", line 9, in <module>
print(primefinder(q))
File "primenumber.py", line 3, in primefinder
for y in range(2, z+1):
TypeError: Can't convert 'int' object to str implicitly
update: I learned how to properly format integers and strings etc. a very long time ago
The input() function by default returns a string as output, you should explicitly covert it into a different type using int(),float() etc.
def primefinder(z):
primenumber_list=[]
for y in range(2, z+1):
if y not in primenumber_list:
print(y)
for x in range(y*y,z+1,y):
primenumber_list.append(x)
q=int(input('Enter maximum:'))
print(primefinder(q))

Is there a way to get the sum of non-zero elements in numpy array? I keep getting a TypeError

I googled this question extensively and I can't figure out what's wrong. I keep getting:
"TypeError: '>' not supported between instances of 'numpy.ndarray' and 'int'".
I searched it and the websites led me to download a package and that still didn't solve my issue. My code looks as follows:
result=[]
FracPos = np.array(result)
for x in lines:
result.append(x.split())
TotalCells = np.array(result)[:,2]
print(type(TotalCells))
print(type(FracPos))
FracPos = np.sum((TotalCells)>0)
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-0972db6a45c4> in <module>
17 TotalCells = np.array(result)[:,2]
18 print(type(TotalCells))
---> 19 FracPos = np.sum((TotalCells)>0)
TypeError: '>' not supported between instances of 'numpy.ndarray' and 'int'
I can't figure out why I get the error at the last line and how to change it. I am very new to Python so I'm sure I'm missing something obvious, but the other questions like this are about nympy.ndarray and strings or lists which I understand why you can't compare.
It is because result is a list containing str objects. If you only have numbers in your array, then do:
result = [float(x) for x in result]
TotalCells = ...
Then, in order to get the sum of positive elements, you would have to do:
FracPos = np.sum(TotalCells[TotalCells > 0])
The line you wrote counts the number of postiive elements, it does not sum them.

Confusion Matrix : RecursionError

I had been trying to replicated an online tutorial for plotting confusion matrix but got recursion error, tried resetting the recursion limit but still the error persists. The code is a below:
log = LogisticRegression()
log.fit(x_train,y_train)
pred_log = log.predict(x_train)
confusion_matrix(y_train,pred_log)
The error I got is :
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-57-4b8fbe47e72d> in <module>
----> 1 (confusion_matrix(y_train,pred_log))
<ipython-input-48-92d5242f8580> in confusion_matrix(test_data, pred_data)
1 def confusion_matrix(test_data,pred_data):
----> 2 c_mat = confusion_matrix(test_data,pred_data)
3 return pd.DataFrame(c_mat)
... last 1 frames repeated, from the frame below ...
<ipython-input-48-92d5242f8580> in confusion_matrix(test_data, pred_data)
1 def confusion_matrix(test_data,pred_data):
----> 2 c_mat = confusion_matrix(test_data,pred_data)
3 return pd.DataFrame(c_mat)
RecursionError: maximum recursion depth exceeded
The shape of the train and test data is as below
x_train.shape,y_train.shape,x_test.shape,y_test.shape
# ((712, 7), (712,), (179, 7), (179,))
Tried with: sys.setrecursionlimit(1500)
But still no resolution.
Looks like you are recursively calling the same function. Try changing the outer function name.
1 def confusion_matrix(test_data,pred_data):
----> 2 c_mat = confusion_matrix(test_data,pred_data)
3 return pd.DataFrame(c_mat)
To
def confusion_matrix_pd_convertor(test_data,pred_data):
c_mat = confusion_matrix(test_data,pred_data)
return pd.DataFrame(c_mat)
log = LogisticRegression()
log.fit(x_train,y_train)
pred_log = log.predict(x_train)
confusion_matrix_pd_convertor(y_train,pred_log)

scikit learn says num samples must be greater than num clusters

Using sklearn.cluster.KMeans. Nearly this exact code worked earlier, all I changed was the way I built my dataset. I have just no idea where even to start... Here's the code:
from sklearn.cluster import KMeans
km = KMeans(n_clusters=20)
for item in dfX:
if type(item) != type(dfX[0]):
print(item)
print(len(dfX))
print(dfX[:10])
km.fit(dfX)
print(km.cluster_centers_)
Which outputs the following:
12147
[1.201, 1.237, 1.092, 1.074, 0.979, 0.885, 1.018, 1.083, 1.067, 1.071]
/home/sbendl/anaconda3/lib/python3.5/site-packages/sklearn/utils/validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)
Traceback (most recent call last):
File "/home/sbendl/PycharmProjects/MLFP/K-means.py", line 20, in <module>
km.fit(dfX)
File "/home/sbendl/anaconda3/lib/python3.5/site-packages/sklearn/cluster/k_means_.py", line 812, in fit
X = self._check_fit_data(X)
File "/home/sbendl/anaconda3/lib/python3.5/site-packages/sklearn/cluster/k_means_.py", line 789, in _check_fit_data
X.shape[0], self.n_clusters))
ValueError: n_samples=1 should be >= n_clusters=20
Process finished with exit code 1
As you can see from the output, there are definitely 12147 samples, which is greater than 20 in most counting systems ;). Additionally they're all floats, so it couldn't be having a problem with that. Anyone have any ideas?

Resources