I have an assignment that asks this:
4)Add a method to filter out tiger in the zoo and look at them. Use regex to achieve this functionality.
Hint: you will have to go over all the animals in the zoo.
I'm not sure how to search a list of class object names using regex. Any hints here would be appreciated greatly!
import functools
import re
class Animal:
def __init__(self):
self.__numberOfLegs = 4
self.__numberOfHands = 0
def look(self):
return "\nNumber of hands: {hand}, Number of legs: {leg}".format(
hand=self.__numberOfHands, leg=self.__numberOfLegs)
class Bird:
def __init__(self):
self.__numberOfLegs = 2
self.__numberOfWings = 2
def look(self):
return "\nNumber of wings: {wing}, Number of legs: {leg}".format(
wing=self.__numberOfWings, leg=self.__numberOfLegs)
class Feline(Animal):
def __init__(self):
Animal.__init__(self)
self.__characteristic = "Felines belong to the cat family"
def look(self):
return super().look() + "\n" + self.get_characteristic()
def get_characteristic(self):
return self.__characteristic
class Tiger(Feline):
def __init__(self):
Feline.__init__(self)
self.__characteristic = "Tigers can roar and are lethal predators\n"
def get_characteristic(self):
return super().get_characteristic() + "\n" + self.__characteristic
class WildCat(Feline):
def __init__(self):
Feline.__init__(self)
self.__characteristic = "Wild cats can climb trees\n"
def get_characteristic(self):
return super().get_characteristic() + "\n" + self.__characteristic
class Canine(Animal):
def __init__(self):
Animal.__init__(self)
self.__characteristic = "Canines belong to the dog family"
def look(self):
return super().look() + "\n" + self.get_characteristic()
def get_characteristic(self):
return self.__characteristic
class Wolf(Canine):
def __init__(self):
Canine.__init__(self)
self.__characteristic = "Wolves hunt in packs and have a leader\n"
def get_characteristic(self):
return super().get_characteristic() + "\n" + self.__characteristic
class FlightBird(Bird):
def __init__(self):
Bird.__init__(self)
self.__characteristic = "Flight birds fly and hunt for food"
def look(self):
return super().look() + "\n" + self.get_characteristic()
def get_characteristic(self):
return self.__characteristic
class Eagle(FlightBird):
def __init__(self):
FlightBird.__init__(self)
self.__characteristic = "Eagles fly extremely high and can see their prey from high up in the sky\n"
def get_characteristic(self):
return super().get_characteristic() + "\n" + self.__characteristic
class Zoo:
def __init__(self):
self.__animalList = list()
self.__birdList = list()
def add(self, living_thing):
if not isinstance(living_thing, Animal) and not isinstance(living_thing, Bird):
raise Exception("Only animals and birds can be passed")
try:
if isinstance(living_thing, Animal):
if len(list(filter(lambda a: type(a) == type(living_thing), self.__animalList))) == 0:
if len(self.__animalList) < 2:
self.__animalList.append(living_thing)
print("Animal Added")
else:
print("Zoo full for animals")
else:
print("Creature already in zoo")
elif isinstance(living_thing, Bird):
if len(self.__birdList) < 1:
self.__birdList.append(living_thing)
print("Bird Added")
else:
print("Zoo full for birds")
except Exception:
print("An error has occurred")
else:
print("Completed without errors\n")
def looking(self):
print(Zoo.__look_all_contents(self.__animalList + self.__birdList))
def find_canine(self):
canine_in_zoo = map(lambda h: h.look(), list(filter(lambda g: isinstance(g, Canine), self.__animalList)))
print(*canine_in_zoo)
def find_tiger(self):
#staticmethod
def __look_all_contents(combined_lists):
if len(list(combined_lists)) == 0:
return "Zoo is empty"
string_reduce_map = functools.reduce(lambda x, y: x + y, map(lambda j: j.look(), list(combined_lists)))
return string_reduce_map
zoo = Zoo()
zoo.add(Tiger())
zoo.add(Wolf())
zoo.add(Eagle())
zoo.looking()
zoo.find_canine()
zoo.find_tiger()
How do I search the list_of_classes with regex?
Related
I'm trying to unit test purchaseItem when there is no positive amount of given product and find_price_of_given_id methods in my Automat class.
import unittest
from Automat import Automat
from Bank import Bank
from Item import Item
from exceptions.NoItemException import NoItemException
class AutomatTest(unittest.TestCase):
def test_checkPriceOfGivenID(self):
bank = Bank()
automat = Automat(bank)
Cola = Item(2)
automat.add_object(Cola)
self.assertEqual(automat.find_price_of_given_id(30), 2)
def test_checkIfPurchaseItemCanBeProcessedWhenNoProduct(self):
bank = Bank()
automat2 = Automat(bank)
Soda = Item(2, 0)
automat2.add_object(Soda)
self.assertEqual(automat2.purchaseItem(30), "Given amount it too small and " \
"no item with " + str(30) + " in automat!")
if __name__ == '__main__':
unittest.main()
If I run test one by one, both are passed. If I run the whole class then it says thattest_checkPriceOfGivenID is failed :
Testing started at 14:12 ...
C:\Users\Admin\PycharmProjects\vending-machine\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2018.3.4\helpers\pycharm\_jb_unittest_runner.py" --path C:/Users/Admin/PycharmProjects/vending-machine/AutomatTest.py
Launching unittests with arguments python -m unittest C:/Users/Admin/PycharmProjects/vending-machine/AutomatTest.py in C:\Users\Admin\PycharmProjects\vending-machine
Ran 2 tests in 0.004s
Error
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\unittest\case.py", line 59, in testPartExecutor
yield
File "C:\ProgramData\Anaconda3\lib\unittest\case.py", line 615, in run
testMethod()
File "C:\Users\Admin\PycharmProjects\vending-machine\AutomatTest.py", line 15, in test_checkPriceOfGivenID
self.assertEqual(automat.find_price_of_given_id(30), 2)
File "C:\Users\Admin\PycharmProjects\vending-machine\Automat.py", line 28, in find_price_of_given_id
raise NoItemException
exceptions.NoItemException.NoItemException
FAILED (errors=1)
Process finished with exit code 1
Automat class
from Item import Item
from exceptions.NoItemException import NoItemException
from exceptions.NoProperAmountException import NoProperAmountException
from Coin import Coin
from decimal import *
class Automat:
item_id = 30
def __init__(self, _bank, objects=None):
self.bank = _bank
if objects is None:
objects = {}
self.objects = objects
self.purchaseItemBank = []
def add_object(self, obj: Item):
id_to_assign = Automat.item_id
self.objects.update({id_to_assign: obj})
Automat.item_id = Automat.item_id + 1
return id_to_assign
def find_price_of_given_id(self, item_id):
if self.objects.get(item_id) is not None:
return self.objects.get(item_id).get_price()
else:
raise NoItemException
def find_amount_of_given_id(self, item_id):
if self.objects.get(item_id) is not None:
return self.objects.get(item_id).get_amount()
else:
raise NoItemException
def checkIfAmountIsPositive(self, item_id):
if self.objects.get(item_id) is not None:
var = True if self.objects.get(item_id).get_amount() > 0 else False
return var
else:
raise NoItemException
def withdrawItem(self, item_id):
self.objects.get(item_id).decrease()
def purchaseItem(self, item_id):
sumOfCoins = 0
if 30 <= item_id <= 50:
lista = []
for i in self.purchaseItemBank:
lista.append(i)
sumOfCoins += i.getCoinValue()
priceOfGivenProduct = self.find_price_of_given_id(item_id)
if sumOfCoins < priceOfGivenProduct:
if not self.checkIfAmountIsPositive(item_id):
return "Given amount it too small and " \
"no item with " + str(item_id) + " in automat!"
else:
raise NoProperAmountException
else:
if not self.checkIfAmountIsPositive(item_id):
return "No item with " + str(item_id) + " in automat!"
a = round(abs(Decimal(priceOfGivenProduct) - sumOfCoins), 2)
listaCopy = self.bank.getSortedBankListWithCoins()
if a > 0:
if len(listaCopy) == 0:
return "Nie mozna wydac"
for i, v in enumerate(self.bank.bank):
if a == 0:
break
elif a >= v.getCoinValue():
a = a - v.getCoinValue()
listaCopy.remove(v)
elif a < v.getCoinValue():
continue
if i + 1 == (len(self.bank.bank)):
return "Nie mozna wydac"
if a > 0:
return "Nie mozna wydac"
self.bank.bank = listaCopy.copy()
self.withdrawItem(item_id)
for iterator in lista:
self.bank.addMoney(iterator)
return "Wydano towar"
else:
raise NoItemException
Item class:
class Item:
def __init__(self, price, amount=5):
self.amount = amount
self.price = price
def get_price(self):
return self.price
def get_amount(self):
return self.amount
def decrease(self):
self.amount -= 1
def __str__(self):
return f"{self.amount} # {self.price}"
Bank class:
class Bank:
def __init__(self):
self.bank = []
def addMoney(self, value):
self.bank.append(value)
def getSumBank(self):
return sum(value.getCoinValue() for value in self.bank)
def getSumOfGivenCoins(self, *args):
suma = 0
for i in args:
suma += i.getCoinValue()
return suma
def getSortedBankListWithCoins(self):
self.bank.sort(key=lambda x: x.getCoinValue(), reverse=True)
listaCopy = self.bank.copy()
return listaCopy
Here:
class Automat:
item_id = 30
item_id is a class attribute - it's shared between all instances of Automat, which is probably how the tests are interfering with one another.
Update:
One way to fix the problem would be to reset the item_id in a setUp method.
What you need is to convert item_id to an instance variable:
class Automat:
def __init__(self, _bank, objects=None):
self.item_id = 30
# rest of init here ...
def add_object(self, obj: Item):
id_to_assign = self.item_id
self.objects.update({id_to_assign: obj})
self.item_id += 1
return id_to_assign
Now all ids will start at 30 and your unit tests will be able to find these items.
I'm trying the implement the following into Python:
NAMES = {"fn" => ["James", "John", "John"], "ln" => ["Smith", "Johnson", "Brown"]}
class RandomNameGenerator
def self.generate
new.to_s
end
def initialize
#fn = NAMES['fn'].sample
#ls = NAMES['ln'].sample
end
def to_s
#fn + " " + #ls
end
end
Which returns:
>> RandomNameGenerator.generate
=> "James Smith"
>> RandomNameGenerator.generate
=> "John Johnson"
My code thus far looks like:
import random
NAMES = {"fn": ["James", "John", "John"], "ln": ["Smith", "Johnson", "Brown"]}
class RandomNameGenerator(object):
#classmethod
def generate(cls):
RandomNameGenerator().__str__
def __init__(self):
self.fn = random.choice(NAMES["fn"])
self.ln = random.choice(NAMES["ln"])
def __str__(self):
return self.fn + " " + self.ln
>>> RandomNameGenerator.generate()
>>> print(RandomNameGenerator.generate())
None
I feel like Ruby's new.to_s isn't the same as Python'sRandomNameGenerator().__str__. What am I not understanding?
You don't return anything in the generate method. Also the __init__ code is called when you initialiaze the class, in you case you are not doing it. You are just calling the class static method. In order to make your code work you have to create a new instance of the RandomNameGenerator in the generate method.
class RandomNameGenerator(object):
#classmethod
def generate(cls):
return cls()
def __init__(self):
self.fn = random.choice(NAMES["fn"])
self.ln = random.choice(NAMES["ln"])
def __str__(self):
return self.fn + " " + self.ln
You are not returning from the method generate():
import random
NAMES = {"fn": ["James", "John", "John"], "ln": ["Smith", "Johnson", "Brown"]}
class RandomNameGenerator(object):
#classmethod
def generate(cls):
return str(cls())
def __init__(self):
self.fn = random.choice(NAMES["fn"])
self.ln = random.choice(NAMES["ln"])
def __str__(self):
return self.fn + " " + self.ln
for i in range(5):
print(RandomNameGenerator.generate())
OUTPUT:
John Johnson
John Brown
James Johnson
James Brown
James Johnson
So for my last assingment in my python course at uni, I have to write a program consisting of three objects, two of which inherit. I keep running into a snag especially with regards to the last two objects. Here is my code:
class Course:
def __init__(self,title="",ID=0):
self._ID = ID
self._title = title
def getID(self):
return self._ID
def getTitle(self):
return self._title
def setTitle(self,title):
self._title = title
def setID(self,ID):
self._ID = ID
def __repr__(self):
return "Title: " + self._title + "ID: " + str(self._ID)
class OfferedCourse(Course):
def __init__(self,title="",ID=0,enrollment=[]):
super().__init__(title,ID)
self._enrollment = len(enrollment)
def getEnrollment(self):
return self._enrollment
def addStudent(self,stu):
if stu in enrollment:
print("Student is already enrolled.")
else:
enrollment.append(stu)
def dropStudent(self,stu):
if stu in enrollment:
def __repr__(self):
super().__repr__() + "Enrollment: " + str(self._enrollment)
class StudentCourse(Course):
def __init__(self,grade,ID=0,title=""):
super().__init__(title,ID)
self._grade = grade
def getGrade(self):
return self._grade
def setGrade(self,grade):
self._grade = grade
def __repr__(self):
super().__repr__() + "Grade: " + str(self._grade)
def main():
#Set primary course
lego=Course("Lego Design",32013)
#display course
print(lego)
#Set OfferedCourse
bonk=OfferedCourse("Matoran History",82932,["Josh","Rick","Greg","Chris"])
#Display OfferedCourse
print(bonk)
#Set StudentCourse
lp=StudentCourse("History of Nu-Metal",57859,82)
#display Student Course
print(lp)
At around line 60 I recieve the error:
TypeError: str returned non-string (type NoneType)
I'm pretty lost as to what is going on.
Your __repr__s don't explicitly return anything. You build up a string, then throw it away, causing None to be implicitly returned instead.
Just add a return:
def __repr__(self):
return super().__repr__() + "Grade: " + str(self._grade)
Adjustments to the source code of the original question:
add missing statement at def dropStudent(self,stu):
add missing return expression for def __repr__(self):
adjust signature of StudentCourse(Course) init to def __init__(self,title,ID,grade): to be in line with parent classes and process given statement StudentCourse("History of Nu-Metal",57859,82) as expected
add missing indentions for def main():
class Course:
def __init__(self,title="",ID=0):
self._ID = ID
self._title = title
def getID(self):
return self._ID
def getTitle(self):
return self._title
def setTitle(self,title):
self._title = title
def setID(self,ID):
self._ID = ID
def __repr__(self):
return "Title: " + self._title + "ID: " + str(self._ID)
class OfferedCourse(Course):
def __init__(self,title="",ID=0,enrollment=[]):
super().__init__(title,ID)
self._enrollment = len(enrollment)
def getEnrollment(self):
return self._enrollment
def addStudent(self,stu):
if stu in enrollment:
print("Student is already enrolled.")
else:
enrollment.append(stu)
def dropStudent(self,stu):
if stu in enrollment:
print("#todo Something is missing here...")
def __repr__(self):
return super().__repr__() + "Enrollment: " + str(self._enrollment)
class StudentCourse(Course):
def __init__(self,title,ID,grade):
super().__init__(title,ID)
self._grade = grade
def getGrade(self):
return self._grade
def setGrade(self,grade):
self._grade = grade
def __repr__(self):
return super().__repr__() + "Grade: " + str(self._grade)
def main():
#Set primary course
lego=Course("Lego Design",32013)
#display course
print(lego)
#Set OfferedCourse
bonk=OfferedCourse("Matoran History",82932,["Josh","Rick","Greg","Chris"])
#Display OfferedCourse
print(bonk)
#Set StudentCourse
lp=StudentCourse("History of Nu-Metal",57859,82)
#display Student Course
print(lp)
main()
My Code:
class SUCHER(EventHandler):
def __init__(self):
self.vokabel = VOKABEL()
EventHandler.__init__(self)
self.button = Button("Suchen!", Point(250,200))
self.button.setFontSize(25)
self.button.setFillColor("lightgrey")
self.button.addHandler(self)
self.lateinischesWort = TextBox(200,50,Point(120,100))
self.übersetzungsText = Rectangle(200,50,Point(380,100))
self.textD = Text("Deutsches Wort", 15, Point(380,50))
self.textL = Text("Lateinisches Wort", 15, Point(120,50))
self.textU = Text(self.vokabel, 25, Point(380,100))
def anzeigenIn(self, Fenster):
Fenster.add(self.button)
Fenster.add(self.übersetzungsText)
Fenster.add(self.lateinischesWort)
Fenster.add(self.textD)
Fenster.add(self.textL)
Fenster.add(self.textU)
def handle(self, Event):
if Event.getDescription() == "mouse click":
self.textL = self.wort
self.textU = self.übersetzung
self.textU.setMessage(self.vokabel)
class BINÄRBAUM:
def __init__(self):
self.wurzel = ABSCHLUSS()
def einfügen(self, Datum):
self.wurzel = self.wurzel.einfügen(Datum)
def inorderAusgeben(self):
self.wurzel.inorderAusgeben()
def preorderAusgeben(self):
self.wurzel.preorderAusgeben()
def postorderAusgeben(self):
self.wurzel.postorderAusgeben()
def suchen(self, Schlüssel):
self.wurzel.suchen(Schlüssel)
class KNOTEN:
def __init__(self, Datum):
self.datum = Datum
self.links = ABSCHLUSS()
self.rechts = ABSCHLUSS()
def einfügen(self, Datum):
if Datum.schlüsselGeben() < self.datum.schlüsselGeben():
self.links = self.links.einfügen(Datum)
else:
self.rechts = self.rechts.einfügen(Datum)
return self
def inorderAusgeben(self):
self.links.inorderAusgeben()
self.datum.informationAusgeben()
self.rechts.inorderAusgeben()
def preorderAusgeben(self):
self.datum.informationAusgeben()
self.links.preorderAusgeben()
self.rechts.preorderAusgeben()
def postorderAusgeben(self):
self.links.postorderAusgeben()
self.rechts.postorderAusgeben()
self.datum.informationAusgeben()
def suchen(self, Schlüssel):
if self.datum.schlüsselGeben() == Schlüssel.casefold():
self.datum.informationAusgeben()
elif self.datum.schlüsselGeben() > Schlüssel.casefold():
self.links.suchen(Schlüssel)
else:
self.rechts.suchen(Schlüssel)
class ABSCHLUSS:
def __init__(self):
pass
def einfügen(self, Datum):
return KNOTEN(Datum)
def inorderAusgeben(self):
pass
def preorderAusgeben(self):
pass
def postorderAusgeben(self):
pass
def suchen(self, Schlüssel):
pass
class VOKABEL:
def __init__(self, Wort, Übersetzung):
self.wort = Wort
self.übersetzung = Übersetzung
def informationAusgeben(self):
print("Das Wort",self.wort,"hat die Bedeutung",self.übersetzung,".")
def schlüsselGeben(self):
return self.wort.casefold()
v = VOKABEL("Nebel", "fog")
s = SUCHER()
b = BINÄRBAUM()
b.einfügen(v)
b.inorderAusgeben()
b.preorderAusgeben()
b.postorderAusgeben()
b.suchen("Nebel")
fenster = Canvas(500,250)
s.anzeigenIn(fenster)
I'm a programmer from Germany and I have a problem.By the way I use the module cs1graphics. I get the Error : builtins.TypeError: init() missing 2 required positional arguments: 'Wort' and 'Übersetzung'
so what can I do to solve this?
class SUCHER(EventHandler):
def __init__(self):
self.vokabel = VOKABEL()
You are instanciating a new VOKABEL class without giving it the 2 arguments it needs. See here the constructor :
class VOKABEL:
def __init__(self, Wort, Übersetzung):
I keep getting this error:
<__main__.product object at 0x0231A7B0>
from the code:
def prnt(self):
print("\n**********************************************************")
print(self.prntlist())
print("Grand total\t\t\t\t$", self.setprice())
print("**********************************************************\n")
def prntlist(self):
x = ''
for i in self.cartlist:
x = i, "/n"
return x
instead of executing the function prntlist it displays that error
full code:
class product(object):
name = ''
price = 0
def __init__(self, name, price):
self.name = name
self.price = price
def prnt(self):
print("\n**********************************************************")
print("Item\t\t\t Price")
print(self.name,"............ $", self.price)
print("\n**********************************************************")
def prntline(self):
x = self.name + ".........." + self.price
return x
class cart(object):
totalprice = 0
cartlist = []
def __init__(self):
self.totalprice = totalprice
self.cartlist = []
def setprice(self):
totprice = self.totalprice
for i in self.cartlist:
self.totalprice += i.price
return totprice
def prnt(self):
print("\n**********************************************************")
print(self.prntlist())
print("Grand total\t\t\t\t$", self.setprice())
print("**********************************************************\n")
def prntlinecart(self):
print("You have purchased: ", self.prntlist())
def prntlist(self):
x = ''
for i in self.cartlist:
x = i, "/n"
return x
def additem(self, item):
self.cartlist.append(item)
print("Ah, fresh out. But we can have it shipped to your house next week")
Ok, I made your example work for me, just to see what is happening:
class product(object):
name = ''
price = 0
def __init__(self, name, price):
self.name = name
self.price = price
def prnt(self):
print("\n**********************************************************")
print("Item\t\t\t Price")
print(self.name,"............ $", self.price)
print("\n**********************************************************")
def prntline(self):
x = self.name + ".........." + self.price
return x
class cart(object):
totalprice = 0
cartlist = []
def __init__(self):
self.totalprice = 0
self.cartlist = []
def setprice(self):
totprice = self.totalprice
for i in self.cartlist:
self.totalprice += i.price
return totprice
def prnt(self):
print("\n**********************************************************")
print(self.prntlist())
print("Grand total\t\t\t\t$", self.setprice())
print("**********************************************************\n")
def prntlinecart(self):
print("You have purchased: ", self.prntlist())
def prntlist(self):
x = ''
print('fff')
for i in self.cartlist:
x = i, "/n"
return x
def additem(self, item):
self.cartlist.append(item)
print("Ah, fresh out. But we can have it shipped to your house next week")
mycart = cart()
RL = product("Red Leicester", 13.99)
RL.prnt()
mycart.additem(RL)
mycart.prnt()
The output is:
**********************************************************
Item Price
Red Leicester ............ $ 13.99
**********************************************************
Ah, fresh out. But we can have it shipped to your house next week
**********************************************************
fff
(<__main__.product object at 0x7ffbe52609e8>, '/n')
Grand total $ 0
**********************************************************
It seems that you ask about this: <__main__.product object at 0x7ffbe52609e8>. As I wrote in the first comment, this is because you are making tuple, not a string when with the following line x = i, "/n".