using python nonzero function inside array brackets - python

I'm looking at the linked GitHub repository and working through the MLA machine learning book, and stumbled across this bit of code and don't understand what's going on here. What is happening here? Is there a better, more explicit way of writing this bit of python?
https://github.com/KUpypy/Past/blob/fd981bfcc3599914be71d38f0412ef2edbcf6046/MLA/(MLA)%20Chp10/(MLA)%20Chp10_Grouping%20unlabeled%20items%20using%20k-means%20clustering.ipynb
bestClustAss[nonzero(bestClustAss[:,0].A == 1)[0], 0] = len(centList)
bestClustAss[nonzero(bestClustAss[:,0].A == 0)[0], 0] = bestCentToSplit
This function is throwing the following error:
local variable 'bestClustAss' referenced before assignment
My thought was something like this:
if(nonzero(bestClustAss[:,0].A == 1)
bestClustAss ....... = len(cenList)
if(nonzero(bestClustAss[:,0].A == 0)
bestClustAss ....... = bestCentToSplit
But I'm still too new to python to figure this out on my own.

Related

Python - Function not updating

I've been facing strange results in a numerical problem I've been working on and since I started to program in python recently, I would like to see if you can help me.
Basically, the program has a function that is minimized for different values in a nested loop. I'll skip the details of the function for simplicity but I checked it several times and it is working correctly. Basically, the code looks like that:
def function(mins,args):
#I'll skip those details for simplicity
return #Value
ranges = ((0+np.pi/100),(np.pi/2-np.pi/100),np.pi/100)
while Ri[0] < R:
Ri[1] = 0; Ri[n-1] = R-(sum(Ri)-Ri[n-1])
while Ri[1] < (R-Ri[0]):
res = opt.brute(function, ranges, args=[args], finish=None)
F = function(res,args)
print(f'F = {F}')
Ri[1] += dR
Ri[2] = R-(sum(Ri)-Ri[n-1])
Ri[0] += dR
So, ignoring the Ri[] meaning in the loop (which is a variable of the function), for every increment in Ri[] the program makes a minimization of mins by the scipy.optimize.brute obtaining res as the answer, then it should run the function with this answer and print the result F. The problem is that it always get the same answer, no matter what the parameters I get in the minimization (which is working fine, I checked). It's strange because if I get the values from the minimization (which is an n-sized array, being n an input) and create a new program to run the same function and just get the result of the function, it returns me the right answer.
Anyone can give me a hint why I'm getting this? If I didn't make myself clear please tell and I could provide more details about the function and variables. Thanks in advance!

Python Time Perf_Counter() CONFUSION

So, really I'm just confused, I've been learning python, and I was given an exercise to find the performance speed of a function, however after finishing the code I received an error in the time output, it was 3.215000000000856e-06, this value varies with every time I run the program though so you probably won't get the same output.(in reality it was less then a second.) I went through the video where it explained how to write how they did it and changed a how I wrote a statement, now my code is Identical, to theirs but with different variable names, I ran the program and the same problem, however they didn't experience this issue, heres the code:
import time
SetContainer = {I for I in range(1002)}
ListContainer = [I for I in range(1002)]
def Search(Value, Container):
if Value in Container:
return True
else:
return False
def Function_Speed(Func, HMT = 1, **arg):
sum = 0
for I in range(HMT):
start = time.perf_counter()
print (Func(**arg))
end = time.perf_counter()
sum = sum + (end - start)
return (sum, )
print (Function_Speed(Search, Value = 402,
Container = SetContainer))
Possible Answers?:
Could it be my hardware? My version of Python is no longer supported(The video is over a year old I'm using 3.6) or it turns out I screwed up.
(Edit:) By the way it does work when the function is printed so this example works, but without print (Func(**arg)) and instead Func(**arg) it doesn't work.
First, your capitalization of variable and function violates convention. Though not a syntax error, it makes it difficult for Python programmers to follow your code.
Second, the result you got makes sense. A single iteration of the search on a modern computer takes very little time. If your printed result was in the form 1.23456e-05, then that is a valid number so small that the default representation shifted to scientific notation.
Add a value for HMT, starting with 100000, and see what is output.

Python Help For Questions

I would like some help with a question on Python. Does anyone know why the coding language is so complicated to learn for some people? I need an answer in 1 week from now.
Thanks.
In my opinion it isnt really that hard. Although, I do forget things here and there. I’d suggest using 3.6 if you are a beginner. Its where I started. If you need a sample program(s), you may use the following.
Printing to console:
print(‘hello’)
Printing to console using variables:
thisIsAString = ‘hello’
print(thisIsAString)
Here are some conditions.
TrueBoolean = True
TrueString = ‘Yes’
TrueInt = 1
TrueList = [‘Yes’, 1, True]
if TrueBoolean:
print(‘Boolean is True’)
if TrueString == ‘Yes’:
print(‘String is “Yes”’)
if TrueInt == 1:
print(‘Int is “Yes”’)
if TrueList == [‘Yes’, 1, True]: # TrueList.contains(INSERT ITEMS HERE) works too.
print(‘List is true’)

Why does this Python code give Runtime Error(NZEC)?

I already read the other questions and answers but couldn't implement any of the solutions to my code. I'm still clueless about the reason why this code gives a runtime error.
I'm trying to submit the code on CodeChef, yet it gives the Runtime Error(NZEC), although the code runs flawlessly on my console for some inputs. Here's my code:
def GetSquares(base):
if not base or base < 4:
return 0
else:
x = (base - 4) - (base % 2) + 1
return x + GetSquares(base - 4)
num_test = int(input())
for test in range(num_test):
base = int(input())
print (int(GetSquares(base)))
Codechef's explanation for NZEC:
NZEC stands for Non Zero Exit Code. For C users, this will be
generated if your main method does not have a return 0; statement.
Other languages like Java/C++ could generate this error if they throw
an exception.
The problem I'm trying to solve:
https://www.codechef.com/problems/TRISQ
The problem description says that the input is constrained to be < 10^4. That's 10,000! Your code will need to make 10,000/4 = 2500 recursive calls to GetSquares, that's a lot! In fact, it's so much that it's going to give you, fittingly, this error:
RuntimeError: maximum recursion depth exceeded
You're going to have to think of a better way to solve the problem that doesn't involve so much recursion! Because you're doing this coding challenge, I'm not going to give a solution in this answer as that would sort of defeat the purpose, but if you'd like some prodding towards an answer, feel free to ask.
The question puts a constraint on the value of 'B' which is 10000 at max, which means there are a lot of recursive calls and giving a runtime error. Try solving using iteration.

"Re-declared Defined Without Usage" One Script but Not The Other?

This sounds like it should be blindingly obvious but there's something quirky going on.
So I have two scripts. Largely the same but a few variances here and there. They both run big loops and they both use global variables. Yes, I know this is bad. Tidying it up is on my to do list but I'm on a time constraint at the moment.
One script works fine. As expected.
The other works fine... for the most part. Then it bugs out once it iterates through the loop again. It's very strange because the code has very little differences but I did pick up on something which I can't explain.
The variable I use to track my position in the loop is set like this in script 1 (which works flawlessly):
global CurrentMatchScan
while True:
print "=Starting Loop="
Loopcounter = 0
CurrentMatchScan = -1
LoadMatch()
The second script has:
global CurrentMatchScan
while True:
print "=Starting Loop="
Loopcounter = 0
CurrentMatchScan = -1
LoadMatch()
However in the second script PyCharm highlights the = -1 part as
Redclared'CurrentMatchScan' defined above without usage
So the obvious assumption is something further up in the code is using it. I do call a function later on which is placed up there...
def LoadMatch():
nextbox1 = LinkList[CurrentMatchScan + 1]
nextbox2 = LinkList[CurrentMatchScan + 2]
But this is only called once CurrentMatchScan is set... and the first script has the exact same code.
Is my IDE just not noticing it on the other script or something? There's a pretty big issue with the looping on the second one and this is the only difference I can see between the two.
I know this doesn't look like a lot to go on but there's not much else to it that I can see. It's barely actually referenced.
I'd really appreciate anyone who can point out how much of an idiot I'm being and missing something really simple.
/edit:
Based on the fact that it does use CurrentMatchScan and calls LoadMatch() for the first iterations properly I'm starting to doubt this is anything but PyCharm trying to warn me I'm potentially doing something silly.
I think if this was the issue it wouldn't work at all so the warning might be a bit of a red herring when it comes to the issue I'm actually facing.

Categories

Resources