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
Related
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
The program below stalls at line:
m = MapH()
This is related with the function:
def next(self):
If redefined as (should be only two underscores):
def __next__(self):
Then, got error message:
instance has no next() method
When hitting the line:
for e in m:
The full code is below:
class MapEntryH:
def __init__(self, key, value):
self.key = key
self.value = value
class MapIteratorH:
def __init__(self,entryList):
self._myEntryList = entryList
self._currItem = 0
def __iter__(self):
return self
def __next__(self):
if self._currItem < len(self._myEntryList):
item = self._myEntryList[self._currItem]
self._currItem += 1
return item
else:
StopIteration
class MapH:
def __init__(self):
self._entryList = list()
def __len__(self):
return len(self._entryList)
def _findPosition(self,key):
for i in range(len(self)):
if self._entryList[i].key == key:
return i
return None
def __contains__(self,key):
ndx = self._findPosition(key)
return ndx is not None
def add(self,key,value):
ndx = self._findPosition(key)
if ndx is not None:
self._entryList[ndx].value = value
return False
else:
entry = MapEntryH(key,value)
self._entryList.append(entry)
return True
def valueOf(self, key):
ndx = self._findPosition(key)
assert ndx is not None, "Invalid map key"
return self._entryList[ndx].value
def remove(self,key):
ndx =self._findPosition(key)
assert ndx is not None,"Invalid map key"
self._entryList.pop(ndx)
def __iter__(self):
return MapIteratorH(self._entryList)
def test_Map():
m = MapH()
m.add(1,"arg")
m.add(2,"eeu")
m.add(3,"ale")
m.add(4,"sue")
m.add(5,"bra")
temp = m.remove(5)
m.add(5,"chl")
m.add(5,"bol")
temp = m.valueOf(5)
temp = m._findPosition(4)
for e in m:
print(e)
me = MapEntryH(1,"arg")
test_Map()
How do I support iteration like:
for e in m:
print(e)
Or containment like:
me = MapEntryH(1,"arg")
if me in m:
print me.value + " is on the map"
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.
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.
How can I access the strings of 'X'
list = [['X','Y','Z'], ['X','Z','Y']]
For example I want to define a function to return True if list[1] of both list is equal to 'X'
You can use all to see if all ith elements in each sublist are the same:
def is_equal(l, i):
first = l[0][i]
return all(sub[i] == first for sub in l)
You might want to catch an IndexError in case i is outside the bounds of and sublist:
def is_equal(l, i):
try:
first = l[0][i]
return all(sub[i] == first for sub in l)
except IndexError:
return False
If you want to explicitly pass a value to check:
def is_equal(l, i, x):
try:
return all(sub[i] == x for sub in l)
except IndexError:
return False
def check_list(list):
for a in list:
if a == "X"
return True
return False
def check_list_list(list):
try:
return check_list(list[1])
except IndexError:
return False