So, it says that create in line 11 is not defined, but it is a recursive function within the class. And In VS Code, it shows me an error at line 6 - it says that I am missing the self argument, but when I add it, it requires 3 arguments in line 23 (why, I can't provide an argument for self, can I ?)
I already tried it with various variations of adding self to the arguments, but nothing worked.
class smarray:
def __init__ (self):
self.array = []
def create(index, dim):
array1 = []
if index < len(dim)-1:
for x in range(0,dim[index]):
array1.append((create(index+1,dim)))
return array1
else:
for x in range(0,dim[index]):
array1.append("nul")
return array1
if index ==0:
self.array = array1
t = smarray()
t = smarray.create(0, [3,4])
error TB:
Traceback (most recent call last):
File "/Users/pc/Documents/VS Code Files/Python testing/testing range.py", line 23, in <module>
t = smarray.create(0, [3,4])
File "/Users/pc/Documents/VS Code Files/Python testing/testing range.py", line 11, in create
array1.append((create(index+1,dim)))
NameError: name 'create' is not defined
There are a couple of things needed to be fixed in order for this code snippet to run:
class smarray:
def __init__(self):
self.array = []
def create(self, index, dim):
array1 = []
if index < len(dim)-1:
for x in range(0, dim[index]):
array1.append((self.create(index+1, dim)))
return array1
else:
for x in range(0, dim[index]):
array1.append("nul")
return array1
if index == 0:
self.array = array1
t = smarray()
my_array = t.create(0, [3, 4])
So, the first fix would be adding the self keyword to the def create() method signature.
Second, in the line array1.append(...) the same self keyword had to be added, so we can call the create method properly: self.create()
And the last one I changed the call to the create method as "instance method" and not as "class method" - I hope I understood correctly what you tried to achieve here. You can read more here.
Pay attention that the last if index==0 is unreachable, thus the code self.array = array1 won't be ever executed. I don't quite sure what you were trying to achieve there.
Related
class HashMap:
def __init__(self, array_size):
self.array_size = size
self.array = [LinkedList() for number in range(array_size)]
I wrote the above code and it shows the following error:
File "script.py", line 7, in __init__
self.array_size = size
NameError: name 'size' is not defined
You are getting this error because you are referring to non existent variable size.
Your variable array_size will get its value when instantiated from outside and the same can be used internally as such. However, if you plan to modify it, first assign it to another variable and then modify the new variable, e.g.,
size = array_size
size = size + 1
But, in the context of the code you have posted, you apparently do not need any additional variable other than self_array being used for storing list of LinkedList objects.
I have reproduced your code (commenting out erroneous code), with a place-holder LinkedList class and it runs without giving any error.
class LinkedList:
def __init__(self):
self.start_node = None
class HashMap:
def __init__(self, array_size):
#self.array_size = size
self.array = [LinkedList() for number in range(array_size)]
a = HashMap(20)
print (len(a.array))
The output is:
20
Hope it helps
First, I am using python 3.6.
I am trying import and use my own .py file in my project. I import my LinkedList.py file and create a Mylist class, which extends the imported file's class.
When I try the construct an instance of the Mylist class, which involves creating an instance of my inheritedLinkedList derived class, I get the following error:
Traceback (most recent call last):
File "*/PycharmProjects/Veri Yapilari/lists.py", line 65, in <module>
test = Mylist()
File "*/PycharmProjects/Veri Yapilari/lists.py", line 38, in __init__
self.linkedlist = inheritedLinkedList()
File "*/PycharmProjects/Veri Yapilari/lists.py", line 8, in __init__
super.__init__()
TypeError: descriptor '__init__' of 'super' object needs an argument
Here's the section of the code where the problem occurs:
test = Mylist()
test.insertFirstM(incomingDataM=4) # <- Causes a TypeError.
Below is the main script in its entirety:
import LinkedList as myLinkedList
class inheritedLinkedList(myLinkedList.DoublyLinkedList):
def __init__(self):
super.__init__()
def raplaceElements(self, dataToBeChanged, incomingData):
position = self.find(dataToBeChanged)
position.data = incomingData
def swapElements(self, swap1, swap2):
position1 = self.find(swap1)
prev1 = position1.previous
next1 = position1.next
position2 = self.find(swap2)
prev2 = position2.previous
next2 = position2.next
prev1.next = position1
position1.previous = prev1
position1.next = next1
next1.previous = position1
prev2.next = position2
position2.previous = prev2
position2.next = next2
next2.previous = position2
def insertBefore(self, incomingData, previousNode=None):
self.insert(incomingData, self.find(previousNode).previous.data)
class Mylist:
def __init__(self):
# self.linkedlist = inheritedLinkedList;
self.linkedlist = inheritedLinkedList() # Per martineau's suggestion.
def replaceElements(self, dataToBeChanged, incomingData):
self.linkedlist.raplaceElements(dataToBeChanged, incomingData)
def swapElements(self, swap1, swap2):
self.linkedlist.swapElements(swap1, swap2)
def insertFirstM(self, incomingDataM):
self.linkedlist.insertFirst(incomingDataM)
def insertLast(self, incomingData):
self.linkedlist.insert(incomingData)
def insertAfter(self, incomingData, incomingNode):
self.linkedlist.insert(incomingData, incomingNode)
def insertBefore(self, incomingData, incomingNode):
self.linkedlist.insert(incomingData, incomingNode)
def remove(self, incomingData):
self.linkedlist.remove(incomingData)
def listprint(self):
self.linkedlist.listprint()
test = Mylist()
test.insertFirstM(4)
The code for the imported LinkedList module (LinkedList.py) can be obtained—if needed—by downloading it from my github repository.
As I said in a comment, you're not using the super built-in correctly. Try do things this way instead (so it's like the example in the linked documentation):
class inheritedLinkedList(myLinkedList.DoublyLinkedList):
def __init__(self):
super().__init__() # Change line to this.
Actually, since the derived class' __init__() is currently doing nothing but that, it's not even necessary because that's what would occur automatically if the subclass didn't define its own. In other words, the following would accomplish the same thing:
class inheritedLinkedList(myLinkedList.DoublyLinkedList):
# ** NOT REALLY NEEDED AT ALL **
# def __init__(self):
# super().__init__()
P.S. You also ought to change the very end of the LinkedList.py script so the last few lines that are there don't execute when it's imported as a module by lists.py:
...
nextNode.previous = previousNode
dataToBeDeleted.next = dataToBeDeleted.previous = None
if __name__ == '__main__': # Should add this, too.
list1 = SinglyLinkedList()
list2 = DoublyLinkedList()
list2.insertFirst(6)
I have a class :
class Difference:
def __init__(self,a1):
self.a1=a1
def computeDifference(self):
d0=max([max(self.a1)-i for i in self.a1])
return d0
maximumDifference=d0
Now when i try to access the class like bellow getting bellow error:
_ = input().strip()
a = [int(e) for e in input().strip().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
error:
Traceback (most recent call last):
File "q.py", line 2, in
class Difference:
File "q.py", line 8, in Difference
maximumDifference=d0
NameError: name 'd0' is not defined
what went wrong?
A few things:
You need to define what d0 is before you can assign it to maximumDifference.
And even if you do define d0 and try to assign it to maximumDifference it won't be reached because that line is after the return statemen.
incorrect indentation but that might be just how you posted your question. I edited your question to fix the indentation error
you can do something like this to fix the above problems:
def computeDifference(self):
d0=max([max(self.a1)-i for i in self.a1])
self.maximumDifference=d0
return d0
The above code would work But it is NOT good practice to define attribute outside of __init__. It is better to define class attributes inside of __init__
class Difference:
def __init__(self,a1):
self.a1=a1
self.maximumDifference = self.computeDifference()
def computeDifference(self):
d0=max([max(self.a1)-i for i in self.a1])
return d0
Your problem is with indentation. Python code must be well indented in order to work properly. Try:
class Difference:
def __init__(self,a1):
self.a1=a1
def computeDifference(self):
d0=max([max(self.a1)-i for i in self.a1])
self.maximumDifference=d0
return d0
Also the line maximumDifference=d0 would never be reached as it was placed after a return and, even if it was, your code wouldn't work since you're using only locally. To store and use maximumDifference outside that function you should store it in self.maximumDifference like the example above.
class stack:
def __init__(self):
self.st = []
def push(self, x):
self.st.append(x)
return self
def pop(self):
return self.st.pop()
Can someone tell me why I can't run python and do stack.push(3) without getting the unbound error. I do the following
>>> from balance import *
>>> stack.push(3)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: unbound method push() must be called with stack instance as first argument (got int instance instead)
>>>
But when I write this code I can push to the stack without error:
import sys
k = sys.argv[1]
class stack:
def __init__(self):
self.st = []
def push(self, x):
self.st.append(x)
return self
def pop(self):
return self.st.pop()
def isEmpty(self): #added an empty fucntion to stack class
return self.st == []
def balance(k):
braces = [ ('(',')'), ('[',']'), ('{','}') ] #list of braces to loop through
st = stack() #stack variable
for i in k: #as it iterates through input
#it checks against the braces list
for match in braces:
if i == match[0]: #if left brace put in stack
st.push(i)
elif i == match[1] and st.isEmpty(): #if right brace with no left
st.push(i) #append for condition stateme$
elif i == match[1] and not st.isEmpty() and st.pop() != match[0]:
st.push(i) #if there are items in stack pop
# for matches and push rest to stack
if st.isEmpty(): #if empty stack then there are even braces
print("Yes")
if not st.isEmpty(): #if items in stack it is unbalanced
print("No")
balance(k) #run balance function
The error is telling you the exact problem:
...method push() must be called with stack instance...
You are doing this:
stack.push(3)
Which is not a stack instance. You are trying to call an instance method as a class method, because you haven't instantiated stack. For example:
>>> st = stack()
>>> st.push(3)
You actually did this properly in your balance function:
st = stack() #stack variable
Now you actually have an instance of stack. You also clearly use it properly further down in your code here, for example:
st.push(i)
Furthermore, you should not be calling stack a variable, it is a class.
You should also reference the PEP8 style guide to adhere to proper conventions. For example, classes should be uppercase: stack should be Stack
I am new in Python and I wrote the following code:
class Frazione:
def __init__(self, Numeratore, Denominatore=1):
mcd=MCD(Numeratore,Denominatore)
self.Numeratore=Numeratore/mcd
self.Denominatore=Denominatore/mcd
def MCD(m,n):
if m%n==0:
return n
else:
return MCD(n,m%n)
def __str__(self):
return "%d/%d" %(self.Numeratore, self.Denominatore)
def __mul__(self, AltraFrazione):
if type(AltraFrazione)==type(5):
AltraFrazione=Frazione(AltraFrazione)
return Frazione(self.Numeratore*AltraFrazione.Numeratore, self.Denominatore*AltraFrazione.Denominatore)
__rmul__=__mul__
Open shell at the same folder of Frazione.py:
>>> from Frazione import Frazione
end then
>>> f=Frazione(10,5)
When I press Enter, I receive this output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".\Frazione.py", line 5, in __init__
mcd=MCD(Numeratore,Denominatore)
NameError: global name 'MCD' is not defined
PS. I apologize for my english!
MCD is a method of Frazione, but you're calling it as if it were a global function. The easiest (and cleanest, IMHO) fix is to just move it outside the class, because it doesn't need to access any class or instance members.
So:
def MCD(m, n):
if m % n == 0:
return n
else:
return MCD(n, m % n)
class Frazione:
# as before but without MCD
If you do want to keep it in the class, then you might rewrite it to be iterative instead of recursive and call it as self.MCD in __init__. That's a good idea anyway, as Python's support for recursion is rather weak.