Why am I getting object has no attribute? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 days ago.
Improve this question
I have written a code that uses python deque from collections. I have created an adapetr class queue.py that handles queue operations. But I am getting error object has no attribute.
queue.py :
from collections import deque
class Queue:
def __int__(self):
self._items = deque()
def enqueue(self, item):
self._items.append(item)
def extend(self, *elements):
self._items.extend(elements)
def dequeue(self):
try:
return self._items.popleft()
except IndexError:
raise IndexError("Dequeue from empty queue") from Queue
def __len__(self):
return len(self._items)
def __contains__(self, item):
return item in self._items
def __iter__(self):
yield from self._items
def __repr__(self):
return f"Queue({list(self._items)})"
graph.py :
from queue import Queue
def getNodeName(rootName):
return input(f"Enter child of node {rootName} : ")
def inputChildren(root):
print(f"Enter stop to stop entering children for node {root} : ")
child = list()
while True:
data = getNodeName(root)
if data.lower() == "stop":
break
child.append()
return child
def inputGraph():
graph = dict()
queue = Queue()
queue.enqueue(input("Enter root name : "))
while len(queue) != 0:
root = queue.dequeue()
rootChildren = inputChildren(root)
queue.extend(rootChildren)
if len(rootChildren) == 0:
continue
else:
graph[root] = rootChildren
if __name__=="__main__":
print(inputGraph())
Output :
Enter root name : A
Traceback (most recent call last):
File "D:\graph.py", line 36, in <module>
print(inputGraph())
File "D:\graph.py", line 23, in inputGraph
queue.enqueue(input("Enter root name : "))
File "D:\queue.py", line 9, in enqueue
self._items.append(item)
AttributeError: 'Queue' object has no attribute '_items'
I have tried searching online but cannot figure out why I am getting this error.

from collections import deque
class Queue:
def __init__(self):
self._items = deque()
def enqueue(self, item):
self._items.append(item)
def extend(self, *elements):
self._items.extend(elements)
def dequeue(self):
try:
return self._items.popleft()
except IndexError:
raise IndexError("Dequeue from empty queue") from Queue
def __len__(self):
return len(self._items)
def __contains__(self, item):
return item in self._items
def __iter__(self):
yield from self._items
def __repr__(self):
return f"Queue({list(self._items)})"
def getNodeName(rootName):
return input(f"Enter child of node {rootName} : ")
def inputChildren(root):
print(f"Enter stop to stop entering children for node {root} : ")
child = list()
while True:
data = getNodeName(root)
if data.lower() == "stop":
break
child.append(data)
return child
def inputGraph():
graph = dict()
queue = Queue()
queue.enqueue(input("Enter root name : "))
while len(queue) != 0:
root = queue.dequeue()
rootChildren = inputChildren(root)
queue.extend(rootChildren)
if len(rootChildren) == 0:
continue
else:
graph[root] = rootChildren
return graph
if __name__=="__main__":
print(inputGraph())

Related

Is it a good idea to have functions whose sole purpose it is to call another function? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 11 months ago.
Improve this question
I wrote code for a Tree traversal. In the Binary_tree class, I wrote three methods: __Inorder, __Postorder, and __Preorder, for tree traversal; and I wrote three other methods to call them and pass in self.root as a parameter so that I don't have to pass it manually every time I want to traverse.
Code:
class Node():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Binary_Tree():
def __init__(self):
self.root = None
def insert(self, data):
new_node = Node(data)
if self.root == None:
self.root = new_node
else:
current_node = self.root
while True:
if data > current_node.data:
if not current_node.right:
current_node.right = new_node
return
else:
current_node = current_node.right
else:
if not current_node.left:
current_node.left = new_node
return
else:
current_node = current_node.left
def inorder_traversal(self):
return self.__Inorder(self.root)
def postorder_traversal(self):
return self.__Postorder(self.root)
def preorder_traversal(self):
return self.__Preorder(self.root)
def __Inorder(self, current_node, visited_node = None):
if visited_node is None:
visited_node = []
if current_node:
self.__Inorder(current_node.left, visited_node)
visited_node.append(current_node.data)
self.__Inorder(current_node.right, visited_node)
return visited_node
def __Postorder(self, current_node, visited_node = None):
if visited_node is None:
visited_node = []
if current_node:
self.__Postorder(current_node.left, visited_node)
self.__Postorder(current_node.right, visited_node)
visited_node.append(current_node.data)
return visited_node
def __Preorder(self, current_node, visited_node = None):
if visited_node is None:
visited_node = []
if current_node:
visited_node.append(current_node.data)
self.__Preorder(current_node.left, visited_node)
self.__Preorder(current_node.right, visited_node)
return visited_node
I showed this code to a guy I know and he said "there is no point in writing a function whose sole instruction is to call another function" and it is bad code writing. So, is it true? If yes, then how should I do it?
Your friend is wrong.
Your function (like inorder_traversal) is not just calling another function: it also disallows the caller to pass any arguments, which are none of their business (current_node, visited_node). And this makes it a good decision to have a clean public method, while the underscored "private" functions deal with implementation details that are reflected in their function parameters.
Not your question, but I do see some room for avoiding code repetition, as your base functions have very similar code. Also you could consider creating generators for them instead of populating lists. You could also consider moving those private methods to the Node class.
For example:
class Node():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def traverse(self, order=0):
if order == -1:
yield self.data
if self.left:
yield from self.left.traverse(order)
if order == 0:
yield self.data
if self.right:
yield from self.right.traverse(order)
if order == 1:
yield self.data
class Binary_Tree():
def __init__(self):
self.root = None
def insert(self, data):
new_node = Node(data)
if self.root == None:
self.root = new_node
else:
current_node = self.root
while True:
if data > current_node.data:
if not current_node.right:
current_node.right = new_node
return
else:
current_node = current_node.right
else:
if not current_node.left:
current_node.left = new_node
return
else:
current_node = current_node.left
def preorder_traversal(self):
if self.root:
return self.root.traverse(-1)
def inorder_traversal(self):
if self.root:
return self.root.traverse(0)
def postorder_traversal(self):
if self.root:
return self.root.traverse(1)
# Demo run
tree = Binary_Tree()
for data in (4,2,3,1,6,5,7):
tree.insert(data)
print(*tree.inorder_traversal())

Queue implementation display function error

class Queue:
def __init__(self): '''initialization of function'''
self.items = []
def is_empty(self): '''Checking if queue is empty or not'''
return self.items == []
def enqueue(self, data): '''Adding value '''
self.items.append(data)
def dequeue(self): ''' Removing value'''
return self.items.pop(0)
def dis(self): '''Printing the stored item in queue'''
print(items)
After that initialization of Queue:
q = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('dis')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
q.enqueue(int(do[1]))
elif operation == 'dequeue':
if q.is_empty():
print('Queue is empty.')
else:
print('Dequeued value: ', q.dequeue())
elif operation == 'dis':
q.dis()
elif operation == 'quit':
break
else:
print("Enter the correct operation")
I'm not able to display the items which are enqueued in the Queue. How could I use dis() method to display items in it?
Think you should print self.items (instead of items)
def dis(self): '''Printing the stored item in queue'''
print(self.items)
That'll output the list using standard formatting, not very pretty so you'll probably want to add some extra logic for pretty-printing.
If you want to restrict the queue size, you could do this by simply ignoring items past a certain limit. For this you'll need to implement a limit, along with logic for checking the limit. For example:
class Queue:
def __init__(self, size=8): '''initialization of function'''
self.items = []
self.size = size
def is_empty(self): '''Checking if queue is empty or not'''
return self.items == []
def enqueue(self, data): '''Adding value '''
if len(self.items) < self.size:
self.items.append(data)
else:
pass # behavior when queue is already full
def dequeue(self): ''' Removing value'''
return self.items.pop(0)
def dis(self): '''Printing the stored item in queue'''
print(items)
class Queue:
items=[]
size=5
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
def dis(self):
print(self.items)
def is_full(self):
if (len(self.zitems)>5):
print("Queue is full")
else:
print("Not full")
Inizialize the items=[] and in dis method add self.items.Also, you could check if the size of the queue is full or not

Adding different information in a python linked list and printing it

I am trying to add different information in a python linked list and printing it, but there seems to be an error. I want to print the ID, the Music and the artist name. This is my error.
Traceback (most recent call last):
File "d:\DSAG\DSAG coding\tempCodeRunnerFile.py", line 101, in <module>
for i in range (0,LinkedList.len_link()):
TypeError: len_link() missing 1 required positional argument: 'list'
This is my code:
class Node :
def __init__(self, newData=None, nextNode=None):
self.data = newData
self.next = nextNode
def getData(self):
return self.data
def setData(self,newData):
self.data = newData
def getNext(self):
return self.next
def setNext(self,newNode):
self.next = newNode
class music :
def __init__(self, ID, musicname, artistname):
self.ID = ID
self.musicname = musicname
self.artistname = artistname
def printlist(self):
print("ID : " + format(self.ID))
print("Music : " + format(self.musicname))
print("Artist : " + format(self.artistname))
class LinkedList :
def __init__(self):
self.head = None
self.size=0
def next(self,newNode):
self.head = newNode
def len_link(list):
temp=list.head
count=0
while(temp):
count+=1
temp=temp.next
return count
def printAll(self):
node = None
if self.head is not None:
node = self.head
print(node.getData())
while(node.getNext() is not None):
node = node.getNext()
print(node.getData())
def AddMusicToTheFront(self,data):
if(self.head==None):
newnode=Node(data)
self.head=newnode
else:
current=self.head
while(current.next!=None):
current=current.next
current.next=Node(data)
self.size=self.size+1
def AddMusicAtPosition (self, data, position):
if(position==0):
newnode=Node(data)
newnode.next=self.head
self.head=newnode
elif(position>self.size):
print("\nOut of Range\n")
elif(position==self.size):
self.AddMusicToTheFront(data)
else:
current=self.head
count=0
while(current!=None):
if(count==position-2):
break
else:
count+=1
current=current.next
newnode=Node(data)
newnode.next=current.next
current.next=newnode
list = LinkedList()
list.AddMusicToTheFront(music(1, "Lauv", "Chasing Fire"))
list.AddMusicToTheFront(music(2, "Panic! At The Disco", "High Hopes"))
list.AddMusicToTheFront(music(3, "Bishop Briggs", "River"))
list.AddMusicAtPosition(music(4,"Why Don't We", "Hooked"),2)
for i in range (0,LinkedList.len_link()):
music.printlist()
This is my desired outcome :
ID:1
Artist : Lauv
Music : Chasing Fire
^This code will be the same for the rest of the information that I will include later
You probably need to define len_link like this:
def len_link(self):
temp=self.head
count=0
while(temp):
count+=1
temp=temp.next
return count
Then you can instantiate a LinkedList object (ll=LinkedList()) and then call len_link() like this ll.len_link().
So your code would look like this:
ll = LinkedList()
ll.AddMusicToTheFront(music(1, "Lauv", "Chasing Fire"))
ll.AddMusicToTheFront(music(2, "Panic! At The Disco", "High Hopes"))
ll.AddMusicToTheFront(music(3, "Bishop Briggs", "River"))
ll.AddMusicAtPosition(music(4,"Why Don't We", "Hooked"),2)
for i in range (0,ll.len_link()):
music.printlist()
for i in range (0,LinkedList.len_link(list)): music.printlist() #pass list in the len_link finction
And music is not set. it might get error because music never initiated and has no attributes, so when it'll try to print, error will occur.
what you need to do is extract an element fromt he list which is a music object then on that obj call printlist()

Understanding Stacks and Queues in python

So i was given this question. Consider the Stack and the Queue class with standard set of operations. Using the Stack and Queue class, what items are contained in them just before the mysteryFunction is called AND just after the mysteryFunction is called?
Here is the code:
def mysteryFunction(s, q):
q.enqueue('csc148')
q.enqueue(True)
q.enqueue(q.front())
q.enqueue('abstract data type')
for i in range(q.size()):
s.push(q.dequeue())
while not s.is_empty():
q.enqueue(s.pop())
if __name__ == '__main__':
s=Stack()
q=Queue()
#About to call mysteryFunction
#What are contents of s and q at this point?
mysteryFunction(s, q)
#mysteryFunction has been called.
#What are contents of s and q at this point?
I'm having trouble understanding object oriented programming as i'm new to this topic. Is there any link that breaks down Stacks and Queues and what they do?
In general, stacks are LIFO and queues are FIFO.
In Python, you can use the collections module to experiment with stacks and queues:
>>> from collections import deque
>>> stack = deque()
>>> stack.append(10)
>>> stack.append(20)
>>> stack.append(30)
>>> stack
deque([10, 20, 30])
>>> stack.pop() # LIFO
30
>>> stack.pop()
20
>>>
>>> queue = deque()
>>> queue.append(10)
>>> queue.append(20)
>>> queue.append(30)
>>> queue
deque([10, 20, 30])
>>> queue.popleft() # FIFO
10
>>> queue.popleft()
20
See following links for more information:
Stack
Queue
Visually these two data structures can be seen in a following way:
Stack:
Description:
There are variations of this data structure. However, in simple terms - as one can observe in the image provided, when you add to this data structure you place on top of what is already there and when you remove you also take from the top. You can view it as a stack of books which you go through one by one starting from the top and all the way down.
Queue
Description:
There are also variations on this particular data structure, however in simple terms - as you can see in the image provided, when you add to this data structure the new element goes in the begining and when you remove its the last element from the list which is being removed. You can imagine it as a queue you got in a shop where you stand behind a lot of people waiting for your turn to come to the counter to pay for your items.
To test this line by line, here are implementations of the classes (wrappers around deque) that are used in the task:
from collections import deque
class Queue(deque):
enqueue = deque.append
dequeue = deque.popleft
def front(self):
return self[-1]
def size(self):
return len(self)
class Stack(deque):
push = deque.append
def is_empty(self):
return not self
STACK #LIFO
class stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop (self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return (len(self.items))
s = stack()
print (s.isEmpty())
>> True
s.push(1)
s.push('3')
s.peek()
>>'3'
s.size()
>> 2
Queue #FIFO
class Queue(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items==[]
def enqueue(self,item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return (len(self.items))
q = Queue()
q.isEmpty()
>>True
q.enqueue(1)
q.enqueue(2)
q.dequeue()
>>1
The first code explains about the stack , we need to create a list and while pushing the element use append and fill the list , similar to what we have in array stack. While pop , pop out the end from where you pushed it.
class Stack:
def __init__(self):
self.stack = []
def push_element(self,dataval):
self.stack.append(dataval)
return self.stack
def pop_element(self):
if len(self.stack) ==0:
print("Stack is empty")
else:
self.stack.pop()
return self.stack
def peek_element(self):
return self.stack[0]
class Queue:
def __init__(self):
self.stack = []
def push_ele(self,data):
self.stack.append(data)
def pop_ele(self):
self.stack.pop(0)
def display(self):
print(self.stack)
class stack:
def __init__(self,n): #constructor
self.no = n # size of stack
self.Stack = [] # list for store stack items
self.top = -1
def push(self): # push method
if self.top == self.no - 1: # check full condition
print("Stack Overflow.....")
else:
n = int(input("enter an element :: "))
self.Stack.append(n) # in list add stack items use of append method
self.top += 1. # increment top by 1
def pop(self): # pop method
if self.top == -1: # check empty condition
print("Stack Underflow....")
else:
self.Stack.pop(). # delete item from top of stack using pop method
self.top -= 1 # decrement top by 1
def peep(self): #peep method
print(self.top,"\t",self.Stack[-1]) #display top item
def disp (self): # display method
if self.top == -1: # check empty condition
print("Stack Underflow....")
else:
print("TOP \tELEMENT")
for i in range(self.top,-1,-1): # print items and top
print(i," \t",self.Stack[i])
n = int(input("Enter Size :: ")) # size of stack
stk = stack(n) # object and pass n as size
while(True): # loop for choice as a switch case
print(" 1: PUSH ")
print(" 2: POP ")
print(" 3: PEEP ")
print(" 4: PRINT ")
print(" 5: EXIT ")
option = int(input("enter your choice :: "))
if option == 1:
stk.push()
elif option == 2:
stk.pop()
elif option == 3:
stk.peep()
elif option == 4:
stk.disp()
elif option == 5:
print("you are exit!!!!!")
break
else:
print("Incorrect option")

Taking elements from list and putting them in a stack with python

This is what i currently have and says that it is missing one argument when it tries to push i
this is the class that I have for this code
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, a):
self._data.append(a)
def top(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data[-1]
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data.pop()
def reverselist():
expression = input("Enter whatever: ")
stacks = ArrayStack
listofstuff = []
for item in expression:
listofstuff.append(item)
print(listofstuff)
for token in listofstuff:
i = str(token)
stacks.push(i)
You need an instance of ArrayStack, not the class itself, change for ArrayStack(), this calls the constructor of your class.
def reverselist():
expression = input("Enter whatever: ")
stacks = ArrayStack()
listofstuff = []
for item in expression:
listofstuff.append(item)
print(listofstuff)
for token in listofstuff:
i = str(token)
stacks.push(i)

Categories