I'm trying to marge two lists that I created through a class to a new list. I use the __add__ function.
But it constantly adds the first two indexes and stops.
This is my code:
class Stack:
def __init__(self):
self.__items = []
self.__top = 0
def is_Empty(self):
return self.__top <= 0
try:
raise Exception('Stack empty.')
except Exception as error:
print(error)
def __str__(self):
"""Print current stack"""
if self.is_Empty() == True:
return "Stack empty"
else:
return "Stack is not empty"
def push(self, item):
"""Push item in stack."""
self.__items.append(item)
self.__top += 1
def pop(self):
"""Remove top of the stack."""
if self.__top <= 0:
return self.is_Empty()
self.__top -= 1
return self.__items.pop()
def top(self):
"""Return top of the stack."""
if self.__top <= 0:
return self.is_Empty()
else:
return self.__items[-1]
def my_stack(self):
"""Show the current stack"""
if self.__items == []:
return self.is_Empty()
else:
return f"The current stack is {self.__items}"
def __add__(self,other):
"""Add two lists together"""
newlst = []
for i, j in zip(self.__items, other.__items):
newlst.append(i+j)
return newlst
def __eq__(self, other):
"""Return True if two list is equal else Return False """
return (self is other) or (self.__items) == (other.__items)
for example:
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack2 = Stack()
stack2.push(4)
stack2.push(5)
stack2.push(6)
Now I'm trying to add the two stacks into stack3:
stack3 = stack + stack2
The result I get is this:
>>> print(stack3)
[5]
My goal is to get stack3 like this:
>>> print(stack3)
[1, 2, 3, 4, 5, 6]
Your current code
def __add__(self,other):
"""Add two lists together"""
newlst = []
for i, j in zip(self.__items, other.__items):
newlst.append(i+j)
return newlst
adds the first elements of each .__items list and returns the result after that.
To add the inner lists one after each other and return as list, this would work:
def __add__(self, other):
"""Add two lists together"""
if isinstance(other,Stack):
return self.__items + other.__items
return [] # or self.__items or raise Exception
To return a new Stack-instance you could do:
def __add__(self, other):
"""Add two lists together"""
if isinstance(other, Stack):
s = Stack()
for item in self.__items:
s.push(item)
for item in other.__items:
s.push(item)
return s
return [] # or self.__items or raise Exception
Related
I am trying to write a class function that removes the first occurence of e (int number) from my array list and for it to return True but if no occurence then return false without adjustment to my array list.
def removeVal(self, e):
A = self.inArray
for x in A:
i+=1
if x == e:
A.remove(i)
self.inArray = A
return True
return False
list = [1,2,2,3,4,5]
list.removeVal(2)
print(list)
class ArrayList:
def __init__(self):
self.inArray = []
self.count = 0
def get(self, i):
return self.inArray[i]
def set(self, i, e):
self.inArray[i] = e
def length(self):
return self.count
def isIn(A, k): # similar to this
# for i in range(len(A)):
# if A[i] == k:
# return True
# return False
You can simply check if e is in the list. list.remove(x) removes the first occurence of x in the list.
You can switch out 'yourlist' with the list you are using.
def removeVal(self, e):
if e in yourlist:
yourlist.remove(e)
return True
return False
I am having trouble sorting this singly linked list. The goal is to sort a polynomial by its exponent in descending order. However I keep getting attribute error: Nonetype has no attribute 'nxt' and I can't understand why. Here is my code below
NodeModule.py
!/usr/bin/python
import sys
sys.setrecursionlimit(4500)
"""A model containing Node class"""
class Node(object):
"""A single node in a data structure"""
def __init__(self, _coefficient, _exponent):
self._coefficient=_coefficient
self._exponent=_exponent
self.nxt=None
#property
def coefficient(self):
return self._coefficient
#coefficient.setter
def coefficient(self, c):
self._coefficient=c
#coefficient.deleter
def coefficient(self):
del self.coefficient
#property
def exponent(self):
return self._exponent
#exponent.setter
def exponent(self, e):
self._exponent=e
#exponent.deleter
def exponent(self):
del self._exponent
#property
def nxt(self):
return self._next
#nxt.setter
def nxt(self, n):
self._next=n
#nxt.deleter
def nxt(self):
del self._next
def __eq__(self, other):
if self._exponent==other._exponent:
return True
else:
return False
def __It__(self, other):
if self._exponent<other._exponent:
return True
else:
return False
def __str(self):
if self._coefficient>=0:
sign="+"
else:
sign=""
return sign +str(self._coefficient) + "X^" +str(self._exponent)
ListModule.py
!/usr/bin/python
from NodeModule import Node
class List(Node):
"""Linked list with pre-defined Node class"""
def __init__(self):
self.head=None
self.count=0
def isEmpty(self):
return self.count==0
def getSize(self):
return self.count
def setNode(self, a=5, b=2):
n=Node(a, b)
return n
def insert(self, index, n):
if index<0 or index > self.count:
return False
if index==0:
n.next=self.head
self.head=n
self.count+=1
return True
walker=self.head
for i in range(index-1):
walker=walker.nxt
n.nxt=walker.nxt
walker.next=n
self.count+=1
return True
def delete(self, index):
if index < 0 or index > self.count:
return False
if index==0:
self.head=self.head.nxt
self.count-=1
return True
walker=self.head
for i in range(index-1):
walker=walker.nxt
walker.nxt=walker.nxt.nxt
self.count-=1
return True
def sort(self):
temp1=self.head.exponent
walker=self.head
j=0
while j < self.count:
for i in range(self.count):
walker=walker.nxt
if i==0:
if walker.nxt.exponent > temp1:
self.insert(0, walker.nxt)
self.delete(walker.nxt)
return True
while walker.nxt is not None and walker.nxt.nxt is not None:
if walker.nxt.exponent < walker.nxt.nxt.exponent:
self.insert(self.getsize(), walker.nxt.nxt)
self.delete(walker.nxt)
return True
return False
j+=1
def str(self):
if self.isEmpty():
return "\nEnd of Polynomial"
walker=self.head
output=[]
while walker is not None:
output.append(str(walker))
walker=walker._next
return " + " .join(output)
main.py
!/usr/bin/python
from NodeModule import Node
from ListModule import List
def readPoly(message):
l=List()
n=input(message)
for i in range(n):
c=input("Enter the coefficient of term %d " % i)
e=input("Enter the exponent of term %d " % i)
l.insert(0, Node(c,e))
return l
def main():
l=readPoly("Enter the number of terms of the polynomial: ")
print l
l.sort()
print l
l.delete(0)
print (l)
if name=='main':
main()
It appears self.head=None, walker=self.head and walker=walker.nxt within the second code block. This means by inference you're trying to get the .nxt property of None (a NoneType), which you set as self.head at the start.
Since the doubly linked list has two dummy nodes, one is the head and the other one is the tail. I can skip the dummy tail node by self.__current == None: raise StopIteration, but I don't know how to pass the dummy head nodes and continue traverse the following node.
class LinkedListDLL:
def __init__(self):
self.__head = NodeDLL(None)
self.__head.set_next(self.__head)
self.__head.set_prev(self.__head)
self.__count = 0
def size(self):
return self.__count;
def is_empty(self):
return self.__count == 0
def add_before(self, item, curr):
new_node = NodeDLL(item)
new_node.set_next(curr)
new_node.set_prev(curr.get_prev())
curr.set_prev(new_node)
new_node.get_prev().set_next(new_node)
self.__count += 1
def add_to_head(self, item):
self.add_before(item, self.__head.get_next())
def add_to_tail(self, item):
self.add_before(item, self.__head)
def remove_from_head(self):
self.remove(self.__head.get_next())
def remove_from_tail(self):
self.remove(self.__head.get_prev())
def remove(self, curr):
curr.get_prev().set_next(curr.get_next())
curr.get_next().set_prev(curr.get_prev())
self.__count -= 1
def __iter__(self):
return LinkedListIterator(self.__head)
class LinkedListIterator:
def __init__(self, head):
self.__current = head
def __next__(self):
if self.__current == None :
raise StopIteration
else:
item = self.__current.set_data.get_next()
self.__current = self.__current.get_next()
return item
You should refactor your code keeping in mind that NodeDLL(None) may not be the same as None. With that done:
def __next__(self):
if not self.__current.get_next():
raise StopIteration
#Skips first value in list, i.e. head
self.__current = self.__current.get_next()
return self.__current
I've created a Set class that has the set types, ListSet and DictSet which are represented by a list and dictionary respectively. Both sets need to be iterable which I've created a SetIterator class to do so, however when I try testing DictSet, I get the following errors:
Traceback (most recent call last):
File "Set.py", line 118, in <module>
inter = e.intersection(t)
File "Set.py", line 22, in intersection
if element in other:
File "Set.py", line 8, in __next__
current_element = self.elements[self.index]
KeyError: 0
It seems as though there's an error within my SetIterator class, and I've tried rewriting the line I think is causing the error, but it hasn't fixed anything
def new(obj, *args, **kwargs):
return type(obj)(*args, **kwargs)
class SetIterator:
def __init__(self, s):
self.elements = s.members()
self.index = 0
def __next__(self):
try:
current_element = self.elements[self.index]
except IndexError:
raise StopIteration()
self.index += 1
return current_element
class Set:
def __iter__(self):
return SetIterator(self)
def intersection(self, other):
new_set = new(self) # to hold intersected set
for element in self:
if element in other:
new_set.add(element)
return new_set
def union(self, other):
new_set = new(self) # to hold unionized set
for element in self:
new_set.add(element)
for element in other:
if element not in new_set:
new_set.add(element)
return sorted(new_set)
def difference(self, other):
new_set = new(self) #to hold set difference
for element in self:
if element not in other:
new_set.add(element)
return new_set
def equals(self, other):
new_set = new(self)
other_set = new(self)
for element in self:
if element in other:
new_set.add(element)
for element in other:
if element in self:
other_set.add(element)
if new_set == other_set:
return True
else:
return False
def notEmpty(self):
empty_set = new(self)
placeholder = new(self)
for element in self:
placeholder.add(element)
if empty_set == placeholder: # If both are equal
return False # means self is empty
else:
return True # means self is not empty
class DictSet(Set):
def __init__(self, elements=[]):
rep = self.rep = {}
for element in elements:
rep[element] = element
def add(self, x):
self.rep[x] = x
# Testing code
if __name__ == '__main__':
e = DictSet([1, 2, 3, 4, 19, 31, 27, 0])
t = DictSet([1, 2, 3, 4])
print(t.rep)
# Testing DictSet
inter = e.intersection(t)
uni = e.union(t)
diff = e.difference(t)
eq = e.equals(t)
print('The intersection of the DictSets is:', inter)
print('The union of the Dictsets is:', uni)
print('The difference of the DictSets is:', diff)
print('Are the two DictSets equal?', eq)
I've tried rewriting SetIterator as:
class SetIterator:
def __init__(self, s):
self.elements = **s.rep**
self.index = 0
def __next__(self):
try:
current_element = self.elements[self.index]
except IndexError:
raise StopIteration()
self.index += 1
return current_element
However I still get the same error and my ListSet prints out the correct sets.
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)