Basically, I'm trying to code the Gauss Elimination(Foward) method, but, when executed, Python raises an exception saying: "Object has no attribute '__getitem__'" when the subtraction between 2 lists occurs.
The complete stacktrace is:
Traceback (most recent call last):
File line 35, in <module>
b=a.GaussForward()
File line 29, in GaussForward
self.a[index][w]=self.a[index][w]-aux[i][w]
TypeError: 'float' object has no attribute 'getitem'
I'll post the code below.
class TestGauss():
a=[]
def __init__(self,A):
self.a=A
def __getitem__(self,i):
return self.a[i]
def __setitem__(self,i,value):
self.a[i]=value
def GaussForward(self):
pivo=0.0
fact=0.0
aux=[]
for i in range(len(self.a)):
pivo=self.a[i][i]
for j in range(i+1,len(self.a[0])):
fact=self.a[j][i]/float(pivo)
print fact
for k in range(len(self.a[0])):
self.a[i][k]*=fact
for w in range(len(self.a[0])):
aux=self.a[i]
if i+1<len(self.a[0]):
index=i+1
self.a[index][w]=self.a[index][w]-aux[i][w]
print self.a
Your problem lies with aux[i][w]. Since you set aux=self.a[i], aux is a flat list (ie. not a list of lists) and thus when you try to access aux[i][w], you're trying to index self.a[i][i][w] which is not correct. I think you meant to do this:
self.a[index][w]=self.a[index][w]-aux[w]
Related
I have a class that starts as follows:
from collections import namedtuple
class Parser:
Rule = namedtuple('Rule', ['lhs', 'rhs', 'dot_pos', 'start_pos', 'end_pos'])
# __init__ ...
Since PyCharm detected all my tuple element namings correctly by giving me proper suggestions, I assumed I did it the right way so far, creating a little Rule class with the syntax shown above.
Now, I have a method within my Parser class that takes a Rule parameter:
def add(self, dot_rule: Rule):
print(dot_rule.end_pos)
# ...
Unfortunately, following error appears as soon as I try to call an element of dot_rule like end_pos:
AttributeError: 'tuple' object has no attribute 'end_pos'
What is it that I misunderstood when using namedtuple?
Edit: I call the method add the following way with lhs, rhs, and pos being some values calculated beforehand:
self.add((lhs, rhs, 0, pos, pos))
I thought since namedtuple is said to be backward-compatible with tuple this would be the correct syntax. Apparently, the parameter is now seen as a plain tuple instead of a Rule. What can I do differently here?
Edit 2: Traceback message:
Traceback (most recent call last):
File "...\earley.py", line 19, in <module>
main()
File "...\earley.py", line 14, in main
parser = Parser(grammar, lexicon, sentence)
File "...\parser.py", line 21, in __init__
self.parse(sentence)
File "...\parser.py", line 56, in parse
self.predict('S', i)
File "...\parser.py", line 41, in predict
self.add((lhs, rhs, 0, pos, pos)) # (X -> .α, i, i)
File "...\parser.py", line 24, in add
print(dot_rule.end_pos)
AttributeError: 'tuple' object has no attribute 'end_pos'
You can try this: essentially you were passing it a class tuple instead of the namedtuple called Rule. See:
Instead of self.add((lhs, rhs, 0, pos, pos))
Use self.add(Parser.Rule(lhs, rhs, 0, pos, pos))
I think the issue is on:
result = CoordinateRow([])
When I debug it I get a Returns None error.
The Error:
Traceback (most recent call last):
line 60, in <module>
interlaced_rows = get_interlace_rows(splits_file)
line 49, in get_interlace_rows
previous_row = previous_row.interlace(row)
AttributeError: 'NoneType' object has no attribute 'interlace'
New error after un-indenting return result (in class CoordinateRow):
Traceback (most recent call last):
line 29, in __getattr__
return self[item]
line 25, in __getitem__
return self._dict[item]
KeyError: 'calculate_new_coord'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
line 59, in <module>
get_new_coordinates(interlaced_rows)
line 54, in get_new_coordinates
new_coordinates = current_coordinates.calculate_new_coord()
line 32, in __getattr__
"'{}' object has no attribute '{}'".format(type(self).__name__, item)
AttributeError: 'Coordinate' object has no attribute 'calculate_new_coord'
From coordinates pypi page:
They can be instantiated in any of the ways a dict can (from another
Mapping, a sequence of pairs, some keyword arguments, or a mixture of
the above).
Example:
Coordinate(x=1, y=2)
Just change this line in get_new_coordinates function:
current_coordinates = Coordinate(int(coordinate[0]), int(coordinate[2]))
to:
current_coordinates = Coordinate(x=int(coordinate[0]), y=int(coordinate[2]))
But, after this, your code get a AttributeError: 'Coordinate' object has no attribute 'calculate_new_coord', because you use a calculate_new_coord method that dont exist in Cordinate class.
EDIT: after change the problem, appear that you dont need the coordinate module. Just remove then, use your own Coordinate class. With your class, change back this line:
current_coordinates = Coordinate(int(coordinate[0]), int(coordinate[2]))
This way, I get the expected output:
6,4
6,5
10,8
8,8
8,6
7,5
7,3
7,4
5,5
4,2
9,7
10,6
5,3
But, if you need to use the coordinates module, you need just do this:
def get_new_coordinates(interlace_rows):
for coordinate in interlace_rows.row:
current_coordinates = Coordinate(order='xy', x=int(coordinate[0]), y=int(coordinate[2]))
new_coordinates = current_coordinates + Coordinate(order='xy', x=1, y=0)
print('%d,%d' % (new_coordinates['x'], new_coordinates['y']))
In this case, you you need to remove or rename your Coordinate class.
I'm trying to make a Taylor series in Python and I don't know how to remove this error:
x=Symbol("x")
def f(x):
return ((math.e)**x)*sin(x)
y=f(x)
print(y.diff(x))
def Taylor(f,x,m,a):
y=f(x)
y2=f
yargliige=0
viga = 10**(-m)
n=0
while True:
if n>10:
return yargliige,n
else:
yargliige+=(y(x)*(x-a)**n)/(factorial(n))
y=y.diff(x)
if abs(yargliige(x)-f(x))<viga:
return yargliige,n
n+=1
print(Taylor(f,-0.3,3,-1))
Error message I get:
Traceback (most recent call last):
File "C:\Users\arman\Desktop\Numbrilised meetodid\praktikum10.py", line 31, in <module>
print(Taylor(f,-0.3,3,-1))
File "C:\Users\arman\Desktop\Numbrilised meetodid\praktikum10.py", line 25, in Taylor
yargliige+=(y(x)*(x-a)**n)/(factorial(n))
TypeError: 'Float' object is not callable
It seems that the original function doesn't accept float, which seems ridiculous.
You've already called y = f(x) which stores the returned float from the function f.
You can not do y() as y is not callable.
Change y = f(x) to y = f and it should solve your use case.
I see that you are trying to call yargliige as a function yargliige(x) which is not applicable since it's a variable not function.
This code keeps giving me the error:
TypeError: 'NoneType' object has no attribute 'getitem'
class d_exposure(object):
def __init__(self):
self.files = glob.glob('C:\files')
def exposure(self,level):
level = inspect.getargspec(d_exposure().exposure)[3][0]
print level
def main():
mp = d_exposure()
mp.exposure(level = 'MID')
It seems that the problem is that it wants a default value for level. However, the traceback shows it is getting a value.
Traceback (most recent call last):
File "C:\Users\Documents\my_scripts\exposure.py", line 58, in <module>
main()
File "C:\Users\Documents\my_scripts\exposure.py", line 54, in main
mp.exposure(level = 'MID')
File "C:\Users\Documents\my_scripts\exposure.py", line 17, in exposure
level = inspect.getargspec(d_exposure().exposure)[3][0]
When I try giving it a default value 'DIM', then the output has 'DIM', even though the call I made was mp.exposure(level = 'MID'). Can someone please help me figure out what I'm doing wrong?
inspect.getargspec(d_exposure().exposure)
This line gives you the following output:
ArgSpec(args=['self', 'level'], varargs=None, keywords=None, defaults=None)
The last entry in that is None, on which you are trying to call the getitem method by accessing the 0th element.
When you give default as 'DIM', the last value in the output of getargspec method is ['DIM'] and hence it gives you 'DIM' as the answer.
When you do this in the main method:
mp.exposure(level = 'MID')
you are giving MID as the parameter and not the default value. Default value can only be given during the function definition.
You haven't stated clearly what exactly you want to do instead, so I can't give you input on that.
Not sure what is wrong with the Python code below. Will appreciate any help. I have looked into here and here, but could not solve my issue.
Code:
class myClass:
def factorial(n,self):
if n == 1:
return 1
else:
return n * self.factorial(n-1)
obj = myClass()
obj.factorial(3)
Error
Traceback (most recent call last):
File "a.py", line 9, in <module>
obj.factorial(3)
File "a.py", line 6, in factorial
return n * self.factorial(n-1)
AttributeError: 'int' object has no attribute 'factorial'
You transposed the parameter names for factorial. The one that refers to the object itself must come first. As it is, you're trying to access the factorial variable of the number that was passed in. Change your definition of factorial to this:
def factorial(self, n):
...
self needs to be the first argument to a class function. Change
def factorial(n,self)
to
def factorial(self, n)
change your method signature to
def factorial(self, n)
instead of
def factorial(n, self)
because when you call a class method via object. python expects reference to the class object as a first parameter. in your case it's 'int'. which is not reference to the class object.