Traceback (most recent call last):
File "C:\Users\sahib navlani\Desktop\gfh.py", line 107, in <module>
main()
File "C:\Users\sahib navlani\Desktop\gfh.py", line 98, in main
crit2.play()
File "C:\Users\sahib navlani\Desktop\gfh.py", line 34, in play
self.play -= play1
TypeError: unsupported operand type(s) for -=: 'instancemethod' and 'int'
I get this error whenever i put this code . I think this due to line self.play -= play
play1 = int(raw_input("Please enter the time for which you want to play = "))
self.play -= play1
It's because self.play is a member method. I think you have done mixing of names of member methods and member names. Give proper names to variables and be clear about the purpose for which you are using it.
I'm only guessing since you haven't shown us the code that's going wrong, but I think you're using the function name as a return value. This is a bad habit that Visual Basic teaches people -- nearly every other language uses return instead, which is what Python does. In Python, you would use a variable (I like to use result) to calculate what you'll return, then put return result at the end of your function. E.g.,
def addTwoNumbers(one, two):
# addTwoNumbers = one + two # Wrong!
result = one + two
return result
In a simple function like this, you could just write return one + two, but in more complicated functions, it's useful to use a variable to calculate the result, then return it at the end. So that's what I showed in this example.
Related
I'm trying to use the aif360 library of ibm for debiasing.
I'm working on a linear regression model and want to try out a metric to calculate the difference between the priviliged and unpriviliged groups.
However when this code is run I get the following error:
TypeError: difference() missing 1 required positional argument: 'metric_fun'
I've looked into the class for this function but they are referring to a metric_fun, also read the docs but didn't get any further.
The function is missing an argument, but I don't know which argument it expects.
A short snippit of the code is:
train_pp_bld = StructuredDataset(df=pd.concat((x_train, y_train),
axis=1),
label_names=['decile_score'],
protected_attribute_names=['sex_Male'],
privileged_protected_attributes=1,
unprivileged_protected_attributes=0)
privileged_groups = [{'sex_Male': 1}]
unprivileged_groups = [{'sex_Male': 0}]
# Create the metric object
metric_train_bld = DatasetMetric(train_pp_bld,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
# Metric for the original dataset
metric_orig_train = DatasetMetric(train_pp_bld,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
display(Markdown("#### Original training dataset"))
print("Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_orig_train.difference())
The stack trace that was given is:
Traceback (most recent call last):
File "/Users/sef/Desktop/Thesis/Python Projects/Stats/COMPAS_Debias_AIF360_Continuous_Variable.py", line 116, in <module>
print("Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_orig_train.difference())
File "/Users/sef/opt/anaconda3/envs/AI/lib/python3.8/site-packages/aif360/metrics/metric.py", line 37, in wrapper
result = func(*args, **kwargs)
TypeError: difference() missing 1 required positional argument: 'metric_fun'
After creating a function:
def privileged_value(self, privileged=False):
if privileged:
return unprivileged_groups['sex_Male']
else:
return privileged_groups['sex_Male']
display(Markdown("#### Original training dataset"))
print("Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_orig_train.difference(privileged_value))
still get a similar error traceback:
Traceback (most recent call last):
File "/Users/sef/Desktop/Thesis/Python Projects/Stats/COMPAS_Debias_AIF360_Continuous_Variable.py", line 123, in <module>
print("Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_orig_train.difference(privileged_value))
File "/Users/sef/opt/anaconda3/envs/AI/lib/python3.8/site-packages/aif360/metrics/metric.py", line 37, in wrapper
result = func(*args, **kwargs)
File "/Users/sef/opt/anaconda3/envs/AI/lib/python3.8/site-packages/aif360/metrics/dataset_metric.py", line 77, in difference
return metric_fun(privileged=False) - metric_fun(privileged=True)
File "/Users/youssefennali/Desktop/Thesis/Python Projects/Stats/COMPAS_Debias_AIF360_Continuous_Variable.py", line 120, in privileged_value
return privileged_groups['sex_Male']
TypeError: list indices must be integers or slices, not str
Could someone please point me in the right direction?
There are no examples available of similar code online.
Regards,
Sef
Looking at the source code for the library on GitHub a reference to a function needs to be passed into difference(self, metric_fun). All difference does is subtract the output of your function with privileged=False as the input with the output of your function with privileged=True as the input.
def difference(self, metric_fun):
"""Compute difference of the metric for unprivileged and privileged
groups.
"""
return metric_fun(privileged=False) - metric_fun(privileged=True)
Create a function like this and pass it into difference.
def privilege_value(privileged=False) -> int:
if privileged:
return unprivileged_groups[0]['sex_male']
else:
return privileged_groups[0]['sex_male']
metric_orig_train.difference(privilege_value)
Well, without knowing anything about the library you're using, the error message still seems pretty clear, especially since you only call difference once, like this:
metric_orig_train.difference()
The error message is telling you that you should be passing an argument in this call. The name of the argument is metric_fun, which suggests to me that you are supposed to pass it a function reference.
NOTE: It is possible that difference() is being called outside your code. When you supply an error message, please always submit the stack trace that came along with it, if there is one. Then we can see exactly where in the code the problem occurred.
I'm learning python, now I'm learning for and while, the exercise that I'm doing asks me to make the square of a number using a for loop.
So I'm trying to make it but I don't know how to solve a problem, that I know why it is there, but I don't know how to solve it.
Anyway here's the code
def main():
#start
givn_n = eval(input("Tell me the number:\n"))
for i in givn_n:
#start
double_givn_n = givn_n ** 2
print(double_givn_n)
#end
return
#end
main()
The error is:
Traceback (most recent call last):
File "C:\Users\Simone\Desktop\progetto python\Tutorial-python\w ext libraries\somma_quadrati.py", line 12, in <module>
main()
File "C:\Users\Simone\Desktop\progetto python\Tutorial-python\w ext libraries\somma_quadrati.py", line 6, in main
for i in givn_n:
TypeError: 'int' object is not iterable
Your question has already been answered but I want to mention about how to improve your code.
eval is a dangerous function. I recommend you to not use it. In your case, int can be called.
What about something else. Simple. Try ast.literal_eval. Secure way of doing the evaluation.
def main():
# start
givn_n = int(input("Tell me the number:\n"))
for i in range(givn_n):
# start
double_givn_n = givn_n ** 2
print(double_givn_n)
#end
return # Your code already ends, I think no need to return :)
#end
main()
Your code needs a small correction
for i in range(givn_n):
I place the following in a .py script. Note the need for absolute value:
#!python
givn_n = abs(int(input("Tell me the number:\n")))
double_givn_n = 0
for i in range(0,abs(givn_n)):
double_givn_n += givn_n
print(double_givn_n)
I am teaching myself Python and am trying out a challenge I found to create a quote program for a gardener. I have almost all of it working and have added in iteration so that the user can make more than one quote without re-starting the program.
It produces the quote perfectly the first time but on the second run it presents this error:
Traceback (most recent call last):
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 105, in <module>
lawn = m2_items("lawn",0)
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 23, in m2_items
minutes = area*time[index]
TypeError: 'float' object is not subscriptable
I have the following code as a function that is producing the error:
def m2_items (item,index):
global costs, time, LABOUR
length = int(input("How long is the "+ item+"?\n"))
width = int(input("How wide is the "+item+"?\n"))
area = length*width
cost_m2 = float(costs[index])
total_cost = area*cost_m2
minutes = area*time[index]
hours = int(minutes/60)
labour = LABOUR*hours
labour_cost=round(labour,2)
m2_details = [area, cost_m2, total_cost,hours, labour_cost]
return m2_details
I have tried re-setting the local variables on the running of the function (but I didn't think this was needed as the variables should be removed from memory once the function has run).
I hope the question is clear and that I can get some insight. To re-iterate, what I want the program to do is allow me to call this function multiple times.
You are using the global time variable, which is initially subscriptable (probably an array). As your program continues, some other part of your code will assign a new value to time, maybe accidentally because you wrote time = some_calculation() instead of time[i] = some_calculation(), or maybe you are using the name time somewhere else without realizing it's already in use.
Do a search for all the places where you use the name time and you will probably find your error.
This is a common problem with global variables. Sometimes something updates them from another part of the code, and the error will sneak up on you like this.
I have an interesting problem. I am -- for shits and giggles -- trying to write a program really shortly. I have it down to 2 lines, but it has a race condition, and I can't figure out why. Here's the gist of it:
imports...
...[setattr(__main__, 'f', [1, 2, ..]), reduce(...random.choice(f)...)][1]...
Every once in a while, the following exception will be generated. But NOT always. That's my problem. I suspect that the order of execution is not guaranteed especially since I'm using the list trick -- I would assume that maybe the interpreter can predict that setattr() returns None and knows that I'm only selecting the 2nd thing in the list, so it defers the actual setattr() to later. But it only happens sometimes. Any ideas? Does CPython automatically thread some things like map, filter, reduce calls?
Traceback (most recent call last):
File "/usr/lib64/python3.4/random.py", line 253, in choice
i = self._randbelow(len(seq))
File "/usr/lib64/python3.4/random.py", line 230, in _randbelow
r = getrandbits(k) # 0 <= r < 2**k
ValueError: number of bits must be greater than zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test4.py", line 2, in <module>
print(" ".join([setattr(n,'f',open(sys.argv[1],"r").read().replace("\n"," ").split(" ")),setattr(n,'m',c.defaultdict(list)),g.reduce(lambda p,e:p+[r.choice(m[p[-1]])],range(int(sys.argv[2])),[r.choice(list(filter(lambda x:[m[x[0]].append(x[1]),x[0].isupper()][1],zip(f[:-1],f[1:]))))[0]])][2]))
File "test4.py", line 2, in <lambda>
print(" ".join([setattr(n,'f',open(sys.argv[1],"r").read().replace("\n"," ").split(" ")),setattr(n,'m',c.defaultdict(list)),g.reduce(lambda p,e:p+[r.choice(m[p[-1]])],range(int(sys.argv[2])),[r.choice(list(filter(lambda x:[m[x[0]].append(x[1]),x[0].isupper()][1],zip(f[:-1],f[1:]))))[0]])][2]))
File "/usr/lib64/python3.4/random.py", line 255, in choice
raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence
I've tried modifying globals() and vars() insetad of using setattr(), but that does not seem to help (same exception sequence).
Here's the actual code:
import sys,collections as c,random as r,functools as g,__main__ as n
print(" ".join([setattr(n,'f',open(sys.argv[1],"r").read().replace("\n"," ").split(" ")),setattr(n,'m',c.defaultdict(list)),g.reduce(lambda p,e:p+[r.choice(m[p[-1]])],range(int(sys.argv[2])),[r.choice(list(filter(lambda x:[m[x[0]].append(x[1]),x[0].isupper()][1],zip(f[:-1],f[1:]))))[0]])][2]))
If you're curious: This is to read in a text file, generate a Markov model, and spit out a sentence.
random.choice()
Well, of course that is nondeterministic. If you are very careful, you could set the seed of the pseudo-random number generator to something constant, and hope that's fabricates the same sequence every time. There's a good chance it will work.
random.seed(42); ...
Alright, here's what actually happened: In my sentence generation, I sometimes hit the last word in the file (which in some cases, depending on the file, does not have a possible successor state). Hence, I'm trying to choose from an empty list in that case.
The below snippet of code keeps returning a "NoneType isn't iterable" error. Why doesn't the if statement catch this?
inset = set()
for x in node.contacted:
print type(x)
if x.is_converted() is True:
nset.add(x)
if x.contacted is None:
memotable[node.gen][node.genind] = nset
else:
nset.union(self.legacy(x, memotable))
memotable[node.gen][node.genind] = nset
Full traceback as requested:
Traceback (most recent call last):
File "F:\Dropbox\CS\a4\skeleton\trialtest.py", line 142, in
test_legacy_and_frac()
File "F:\Dropbox\CS\a4\skeleton\trialtest.py", line 125, in
test_legacy_and_frac
cunittest2.assert_equals(set([n10,n12,n21]), t.legacy(n00,mtable))
File "F:\Dropbox\CS\a4\skeleton\trial.py", line 138, in legacy
nset.union(self.legacy(x, memotable))
File "F:\Dropbox\CS\a4\skeleton\trial.py", line 138, in legacy
nset.union(self.legacy(x, memotable))
TypeError: 'NoneType' object is not iterable
The if statement guarantees that x.contacted isn't None.
But x.contacted isn't what you're trying to iterate or index, so it isn't guarding anything.
There's no reason memotable or memotable[node.gen] can't be None even though x.contacted is something else. For that matter, we have no idea of what the code inside self.legacy(x, memotable) does—maybe it tries to iterate x, or other_table[x], or who knows what, any of which could be None.
This is why you need to look at the entire traceback, not just the error string. It will tell you exactly which statement failed, and why.
And now that you've pasted the traceback:
File "F:\Dropbox\CS\a4\skeleton\trial.py", line 138, in legacy nset.union(self.legacy(x, memotable))
Yep, it's something that happens inside that self.legacy line, and it has absolutely nothing to do with x.contacted. The problem is almost certainly that your self.legacy method is returning None, so you're doing nset.union(None).
Again, whether x.contacted is or is not None is completely irrelevant here, so your check doesn't guard you here.
If you want us to debug the problem in that function, you will have to give us the code to that function, instead of code that has nothing to do with the error. Maybe it's something silly, like doing a + b instead of return a + b at the end, or maybe it's some deep logic error, but there's really no way we can guess.
Check the value of memotable and memotable[node.gen] as it can not be said to guaranteed that they are not None if x.contacted is not None (without the code).
If you mention the values of the variables here and Post the Full Traceback, we may be able to point out the problem more precisely.
The exception occurs because the function call self.legacy(x, memotable) returns None.
The traceback indicates the error occurs in nset.union(self.legacy(x, memotable)), and set.union() raises that exception when its argument is None. (I'm assuming nset is a set. Your code defines inset = set(), but does not show where nset comes from)
>>> set().union(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable