What is the best way to provide a string representation of everyone in the queue. A person with a value 0 or less will have infinite number of turns. When a person is removed from the queue, they are re-added to the queue if they still have turns left. My queue stays empty. The goal is to follow FIFO rules when it comes to queue.
class Queue:
# implementation of a Queue
def __init__(self):
# empty queue.
self.queue = []
def enqueue(self, value):
# Add an item to the queue - run code queue is empty
self.queue.insert(0, value)
def dequeue(self):
# Remove the next item from the queue.
value = self.queue[0]
del self.queue[0]
return value
def is_empty(self):
# check to see if queue is empty
return len(self.queue) == 0
def __len__(self):
return len(self.queue)
def __str__(self):
result = "["
for item in self.queue:
result += str(item) + ", "
result += ", "
result += "]"
return result
class Taking_Turns_Queue:
class Person:
# define name and turns
def __init__(self, name, turns):
self.name = name
self.turns = turns
def __str__(self):
# display a person
if self.turns <= 0:
result = "({}:Forever)".format(self.name)
else:
# Add zero and 1 below. THe orginal code had zero.
result = "({}:{})".format(self.name, self.turns)
return result
def __init__(self):
"""
Start with an empty queue
"""
self.people = Queue()
def add_person(self, name, turns):
"""
Add new people to the queue with a name and number of turns
"""
person = Taking_Turns_Queue.Person(name, turns)
self.people.enqueue(person)
def get_next_person(self):
if self.people.is_empty():
print("No one in the queue.")
else:
person = self.people.dequeue()
if person.turns > 1:
person.turns -= 1
self.people.enqueue(person)
print(person.name)
def __len__(self):
"""
Support the len() function
"""
return len(self.people)
def __str__(self):
"""
Provide a string representation of everyone in the queue
"""
return str(self.people)
# Test Cases
# Test 1
# Scenario: Create a queue with the following people and turns: Bob (2), Tim (5), Sue (3) and
# run until the queue is empty
# Exepcted Result: Bob, Tim, Sue, Bob, Tim, Sue, Tim, Sue, Tim, Tim
print("Test 1")
players = Taking_Turns_Queue()
players.add_person("Bob", 2)
players.add_person("Tim", 5)
players.add_person("Sue", 3)
print(players)
while len(players) > 0:
players.get_next_person()
# Defect(s) Found:
print("=================")
# Test 2
# Scenario: Create a queue with the following people and turns: Bob (2), Tim (5), Sue (3)
# After running 5 times, add George with 3 turns. Run until the queue is empty.
# Exepcted Result: Bob, Tim, Sue, Bob, Tim, Sue, Tim, George, Sue, Tim, George, Tim, George
print("Test 2")
players = Taking_Turns_Queue()
players.add_person("Bob", 2)
players.add_person("Tim", 5)
players.add_person("Sue", 3)
for i in range(5):
players.get_next_person()
print(players)
players.add_person("George", 3)
print(players)
while len(players) > 0:
players.get_next_person()
# Defect(s) Found:
print("=================")
# Test 3
# Scenario: Create a queue with the following people and turns: Bob (2), Tim (Forever), Sue (3)
# Run 10 times.
# Exepcted Result: Bob, Tim, Sue, Bob, Tim, Sue, Tim, Sue, Tim, Tim
print("Test 3")
players = Taking_Turns_Queue()
players.add_person("Bob", 2)
players.add_person("Tim", 0)
players.add_person("Sue", 3)
print(players)
for i in range(10):
players.get_next_person()
print(players)
# Defect(s) Found:
print("=================")
# Test 4
# Scenario: Try to get the next person from an empty queue
# Exepcted Result: Error message should be displayed
print("Test 4")
players = Taking_Turns_Queue()
players.get_next_person()
# Defect(s) Found:
Your FIFO isn't a FIFO. Start with something like this before complicating things with people and turn counts.
class FIFO:
def __init__(self):
self.buffer = []
def add(self,item):
self.buffer.insert(0,item)
def get(self):
return self.buffer.pop()
def __str__(self):
if len(self.buffer) == 0:
return "[]"
out = "[" + ''.join([f'{item},' for item in self.buffer])
return out[:-1]+"]"
mybuf = FIFO()
mybuf.add("one")
mybuf.add("two")
mybuf.add("three")
assert mybuf.buffer == ["three", "two", "one"]
_item = mybuf.get()
mybuf.add(_item)
assert mybuf.buffer == ["one", "three", "two"]
print("All tests passed.")
# All tests passed.
Once that's working, then you can take baby steps toward your goal.
class FIFO:
def __init__(self):
self.buffer = []
def add(self,item):
if item["Turns"] > 0:
self.buffer.insert(0,item)
def get(self):
person = self.buffer.pop()
person["Turns"] -= 1
return person
def __str__(self):
if len(self.buffer) == 0:
return "[]"
out = "[" + ''.join([f'{item},' for item in self.buffer])
return out[:-1]+"]"
def items(self):
return len(self.buffer)
# Test 1
# Expected result: Bob Tim Sue Bob Tim Sue Tim Sue Tim Tim
mybuf = FIFO()
mybuf.add({"Name":"Bob","Turns":2})
mybuf.add({"Name":"Tim","Turns":5})
mybuf.add({"Name":"Sue","Turns":3})
debug = False # Set this to true for more information
output = []
while mybuf.items() > 0:
person = mybuf.get()
if debug:
print(f"Got: {person['Name']}, Remaining turns: {person['Turns']}")
output.append(person["Name"])
mybuf.add(person)
if debug:
print(f"Buffer is: {mybuf}\n")
print(' '.join(output))
# Bob Tim Sue Bob Tim Sue Tim Sue Tim Tim
Related
I have a class I've imported into a Python file. But my code is printing the location of the object not the data stored in the object. It is giving me this output, '<Chapter_10_Program_Exercise_5.RetailItem object at 0x10e281520>' which I think is the location but how can I change that? Here's the code and a picture of the python terminal output.
class RetailItem:
# __init__ method initializes the attributes.
def __init__(self, description, units, price):
self.__item_description = description
self.__units_in_inventory = units
self.__price = price
# The set_item_description method gets the item type.
def set_item_description(self, description):
self.__item_description = description
# The set_units_in_inventory method gets number of items available.
def set_units_in_inventory(self, units):
self.__units_in_inventory = units
# The set_price method gets the cost of item.
def set_price(self, price):
self.__price = price
# The get_item_description method returns the item type.
def get_item_description(self):
return self.__item_description
# The get_units_in_inventory returns the number of items available.
def get_units_in_inventory(self):
return self.__units_in_inventory
# The get_price method returns the cost of item.
def get_price(self):
return self.__price
from Chapter_10_Program_Exercise_5 import RetailItem
class CashRegister:
# The __init__ method initializes the attributes.
def __init__(self):
self.__items = []
def clear(self):
self.__items = []
def purchase_item(self, retail_item):
self.__items.append(retail_item)
print('The item was added to the cash register.')
def get_total(self):
total_cost = 0.0
# for loop
for item in self.__items:
total_cost = total_cost +item.get_price()
return total_cost
def display_items(self):
print('The items in the cash register are:')
for item in self.__items:
print(item)
PANTS = 1
SHIRT = 2
DRESS = 3
SOCKS = 4
SWEATER = 5
def main():
pants = RetailItem('Pants', 10, 19.99)
shirt = RetailItem('Shirt', 15, 12.50)
dress = RetailItem('Dress', 3, 79.00)
socks = RetailItem('Socks', 50, 1.00)
sweater = RetailItem('Sweater', 5, 49.99)
sale_items = {PANTS:pants, SHIRT:shirt, DRESS:dress, SOCKS:socks, SWEATER:sweater}
register = CashRegister()
checkout = 'N'
while checkout =='N':
# Call the get_user_option and it is assigned to the user_option
user_option = get_user_option()
# Sale_items of argument user_option is assigned to the item
item= sale_items[user_option]
# If condition to check the items in the items_in_inventory
if item.get_units_in_inventory()== 0:
print('The item is out of stock.')
else:
register.purchase_item(item)
# New item is updated and it is assigned to the new_item
new_item = RetailItem(item.get_item_description(),
item.get_units_in_inventory()-1,
item.get_price())
# Item is updated according to the user selected option
sale_items[user_option] = new_item
# The user input is assigned to the attribute checkout
checkout = input('Are you ready to check out (Y/N)? ')
print()
print('Your purchase total is:',\
format(register.get_total(),'.2f'))
print()
register.display_items()
register.clear()
# Define the get_user_option() method to print the menu items
def get_user_option():
print('Menu')
print('-------------------')
print('1. Pants')
print('2. Shirt')
print('3. Dress')
print('4. Socks')
print('5. Sweater')
print()
option = int(input('Enter the menu number of the item you would like to purchase: '))
print()
while option > SWEATER or option < PANTS:
option = int(input('Please enter a valid item number: '))
return option
main()
Python Terminal Output
This is how python manages the printing of objects. If you want to print attributes you need to tell python which representation you want for your object.
You can do that by implementing these methods in the object class:
class RetailItem:
.
.
.
def __repr__(self):
return "RetailItem()"
def __str__(self):
return "" + self.__item_description + str(self.__units_in_inventory) + str(self.__price)
Note that the two methods will be automatically called in different situations:
>>> ri = RetailItem()
>>> ri
RetailItem()
>>> print(ri)
description 2.0 13.99
Since all variables within RetailItem are private, you'd
need to use the getter method (get_*()) to grab the info.
So to apply that to your display_items() method:
def display_items(self):
print('The items in the cash register are:')
for item in self.__items:
print("Description: %s, Units in Inventory: %d, Price: %0.2f" %
(item.get_item_description(),
item.get_units_in_inventory(),
item.get_price())
I've spent an hour or two collectively now trying to figure this problem out but I'm not getting any results. In my program when a defending animal is "killed" it should be deleted from it's registry, but no matter what I do I can't seem to get that to happen. In this instance if I were to initiate a hunter and a buffalo then attack() the buffalo with the hunter the buffalo should be killed and removed from it's classes registry but I can't get python to select that specific buffalo from the registry.
Any help is appreciated.
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
class Buffalo(object):
__metaclass__ = IterRegistry
_registry = []
hp = 1
price = 150
attacks = 0
regeneration = 2
def __init__(self, name):
self._registry.append(self)
self.name = name
def createBuffalo():
for i in range(len(Buffalo._registry),len(Buffalo._registry)+1):
varname = ("b" + str(i))
globals()[varname] = Buffalo("b" + str(i))
class Wolf:
__metaclass__ = IterRegistry
_registry = []
hp = 1
price = 0
attacks = 2
regeneration = 1.5
def __init__(self, name):
self._registry.append(self)
self.name = name
def createWolf():
for i in range(len(Wolf._registry),len(Wolf._registry)+1):
varname = ("w" + str(i))
globals()[varname] = Wolf("w" + str(i))
class Hunter:
__metaclass__ = IterRegistry
_registry = []
hp = 2
price = 0
attacks = 1
regeneration = 0
balance = 0
def __init__(self, name):
self._registry.append(self)
self.name = name
def createHunter():
for i in range(len(Hunter._registry),len(Hunter._registry)+1):
varname = ("h" + str(i))
globals()[varname] = Hunter("h" + str(i))
def attack(attacker, target):
if attacker.attacks >= 1:
target.hp -= 1
if target.hp == 0:
if type(attacker) == Hunter:
attacker.balance += 150
print(target)
if type(target) == Wolf:
del Wolf._registry[[n for n in Wolf._registry if n == target]]
if type(target) == Hunter:
del Hunter._registry[[n for n in Hunter._registry if n == target]]
if type(target) == Buffalo:
del Buffalo._registry[[n for n in Hunter._registry if n == target]]
One more note, the reason I have double brackets is because it was incorrect syntax with single brackets but the syntax was fine with doubles.
If you need any more code, ask in a comment below (I have not included all of it but it should be enough).
The issue you're trying to solve is caused by trying to use a list as an index to be removed from your list
[n for n in Wolf._registry if n == target]
All you're trying to get out of this list comprehension is the target, so just use that.
Wolf._registry.remove(target)
Using the pre-loaded class Person
Using the Person class, write a function print_friend_info(person) which accepts a single argument, of type Person, and:
prints out their name
prints out their age
if the person has any friends, prints 'Friends with {name}'
Write a function create_fry() which returns a Person instance representing Fry. Fry is 25 and his full name is 'Philip J. Fry'
Write a function make_friends(person_one, person_two) which sets each argument as the friend of the other.
I have gotten the right output with what needs to be printed but when I try run the code through our code Analyzer it says this error:
"You need to print the name of the person's friend in print_friend_info"
class Person(object):
def __init__(self, name, age, gender):
"""Construct a person object given their name, age and gender
Parameters:
name(str): The name of the person
age(int): The age of the person
gender(str): Either 'M' or 'F' for male or female
"""
self._name = name
self._age = age
self._gender = gender
self._friend = None
def __eq__(self, person):
return str(self) == str(person)
def __str__(self):
if self._gender == 'M':
title = 'Mr'
elif self._gender == 'F':
title = 'Miss'
else:
title = 'Ms'
return title + ' ' + self._name + ' ' + str(self._age)
def __repr__(self):
return 'Person: ' + str(self)
def get_name(self):
"""
(str) Return the name
"""
return self._name
def get_age(self):
"""
(int) Return the age
"""
return self._age
def get_gender(self):
"""
(str) Return the gender
"""
return self._gender
def set_friend(self, friend):
self._friend = friend
def get_friend(self):
"""
(Person) Return the friend
"""
return self._friend
def print_friend_info(person):
person_name = person.get_name()
person_age = person.get_age()
person_gender = person.get_gender()
person_friend = person.get_friend()
print (person_name)
print (person_age)
if person_friend == None:
return
else:
friendd = person_friend
nameoffriend = friendd.get_name()
print ('Friends with', nameoffriend)
return
def create_fry():
fry = Person("Philip J. Fry", 25, "M")
return fry
def make_friends(person_one, person_two):
made_friend1 = person_one.set_friend(person_two)
made_friend2 = person_two.set_friend(person_one)
return
--------- Test 1 ---------
Expected Output: Code Analyser
Test Result:
----- Analysis Errors -----
You need to print the name of the person's friend in print_friend_info
Input: bob = Person('Bob Smith', 40, 'M')
--------- Test 2 ---------
Expected Output: print_friend_info(bob)
Code Output: Bob Smith 40
Test Result: Correct!
Input: ed = Person('Ed', 8, 'M')
--------- Test 3 ---------
Expected Output: bob.set_friend(ed)
Code Output: Bob Smith 40 Friends with Ed
Test Result: Correct!
Input: fry = create_fry()
--------- Test 4 ---------
Expected Output: str(fry) -> 'Mr Philip J. Fry 25'
Test Result: Correct!
Input: leela = Person('T. Leela', 22, 'F')
--------- Test 5 ---------
Expected Output: make_friends(fry, leela)
Test Result: Correct!
I am aware that there is another post asking about simulated printers but I didn't find any actual answers to my own question there.
class LinkedQueue :
class _Node :
__slots__ = '_element', '_next'
def __init__(self, element, next = None):
self._element = element
self._next = next
def __init__(self) :
self._head = None
self._tail = None
self._size = 0
def __len__(self) :
return self._size
def is_empty(self) :
return self._size == 0
def first(self) :
if self.is_empty() :
raise Empty('Queue is empty')
return self._head._element
def dequeue(self) :
if self.is_empty():
raise Empty('Queue is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.is_empty() :
self._tail = None
return answer
def enqueue(self, e) :
newest = self._Node(e,None)
if self.is_empty() :
self._head = newest
else :
self._tail._next = newest
self._tail = newest
self._size += 1
class Printer:
def __init__(self, name, job_queue):
self._name = name
self._job_queue
self._current_job = None
class Empty(Exception) :
pass
def main():
p_jobs = LinkedQueue()
red = Printer("Red", p_jobs) # Creates Printer Red
green = Printer("Green", p_jobs) # Creates Printer Green
print("\nOptions:\n 1. Add Job \n 2. Print Pages \n 3. Status \
\n 4. Quit")
i = 0
while True:
n = str(input("\nChoice (Type the number): "))
if n == '1': # Add Job
i += 1
p = int(input("\nHow many pages? "))
j = p_jobs.job_list(i,p,next)
p_jobs.enqueue(j)
if n == '2': # Print Job
print()
p_jobs.dequeue()
i -= 1
if n == '3': # Status
print()
if n == '4': # Quit
print("\nGoodbye!")
break
This is the provided code for us. We are supposed to simulate two printers that print out pages from jobs using LinkedQueue and Node.
I have the main function barebones w/c consists of 4 options:
Add Job, Print Jobs, Status, and Quit
I have trouble understanding how to use (refer) to the enqueue and dequeue methods. Can somebody break down each part of this program so I can at least understand where to start. I also would appreciate any hints that tell me where to go from here. Thank you.
EDIT: I added my main function w/c is basically just a UI
While this is by no means a complete answer, it shows how to print out what's currently in a LinkedQueue instance.
First, add the following method to the class. It will allow the contents to be iterated.
class LinkedQueue:
def __iter__(self):
if self.is_empty():
return None # No jobs in print queue.
cur = self._head
while cur:
yield cur._element
cur = cur._next
Here's something demonstrating how to use it:
def test():
q = LinkedQueue() # Create a queue.
# Add some jobs to the LinkedQueue.
for j in range(3):
pages = randint(1, 10)
q.enqueue(('job #{}'.format(j), pages))
# Show what's currently in the LinkedQueue.
for v in q:
print(v)
# Modify the LinkedQueue and then show what's left in it.
j = q.dequeue()
print('\nafter removing one job')
for v in q:
print(v)
The laughs parking garage contains a single lane that hold up to ten cars. Cars arrive at the south end of the garage and leave from the north end. If a customer arrives to pick up a car
that is not northernmost, all the cars to the north of his car are moved out, his car is driven out,
and the others cars are restored in the same order that they were in originally.
Whenever a car leaves, all the cars to the south are moved forward. So that at all the
times all the empty spaces are in the south part of the garage.
Write python program to reads a group of input lines. Each line contains an āaā arrival or
a ādā departure and a license plate number. Cars are assumed to arrive and depart in the order
specified by the input. The program should print a message each time that a car arrives or
departs. When a car arrives, the massage should specify whether or not there is room for the car
in garage. If there is no room for a car, the car waits until there is room or until a departure line is
read for the car. When room becomes available, another massage should be printed. When a car
departs, the massage should include the number of times the car was moved within the garage
(including the departure itself but not the arrival), this number is 0 if the car departs from the
waiting line.
this is my code. i stuck in middle of the code. i made a queue to park the cars. i don't no how to reassemble the cars when a middle car is departed. and i want a way to print the number of moves before the car depart in park. so anyone can help me?`
class Stack:
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)
class Queue:
def __init__(self,maxSize):
self.items =[]
self._count = 0
self._front = 0
self._back = maxSize - 1
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)
def index(self,item):
return self.items.index(item)
q1park = Queue(maxSize=10)
q2wait= Queue()
q3assemble= Queue()
x =raw_input("Car number: ")
def cararrival():
if x[0]=="a":
while q1park.size ==10:
q1park.enqueue(x[1:len(x)])
print(x + "car is arrived")
if q1park.size ==10:
print("No room available in the garage")
x1=raw_input("do you want to wait: ")
if x1=="yes":
q2wait.enqueue(x[1:len(x)])
elif x1=="no":
print("see you next time")
else:
print("Enter yes or no")
def cardepart():
if x[0]=="d":
if x[1:len(x)] in q1park:
while not q1park.index(x[1:len(x)])==0:
q3assemble.enqueue(q1park.dequeue())
q3assemble.dequeue()
while not q3assemble.isEmpty:
My answer for above question is here.
#creating a class for car
class Car:
#initialization and creating properties
def __init__(self, licenseNum):
self.licenseNum = licenseNum
self.moveCount = 0
#increase the moveCount by 1
def move(self):
self.moveCount += 1
#get information to a string
def toString(self):
return "Car {0}\tmoves:{1}".format(self.licenseNum, self.moveCount)
#creating queue class for cars
class CarQueue:
#initialization
def __init__(self):
self.carList = []
#add car to the queue
def enqueue(self, car):
self.carList.append(car)
#remove car from the queue
def dequeue(self):
return self.carList.pop(0)
#return the car by license plate number
def getCar(self, licenseNum):
for car in self.carList:
if car.licenseNum == licenseNum:
return car
#check whether license plate number is in the car list or not
def contains(self, licenseNum):
return self.getCar(licenseNum)!=None
#remove car from the list
def remove(self, car):
if self.contains(car.licenseNum):
self.carList.remove(car)
#return the number of cars in the list
def size(self):
return len(self.carList)
#check whether list is empty of not
def isEmpty(self):
return self.size()==0
#return the index of the car in the list
def positionOf(self, car):
return self.carList.index(car)
#move forward all the cars in southern side of the position.
def moveCarsFrom(self, position):
for c in self.carList[position:]:
c.move()
#get information to a string
def toString(self):
carNameList = []
for car in self.carList:
carNameList.append(car.licenseNum)
return "[{0}]".format(" ".join(carNameList))
#creating class for the garage
class Garage:
#initialization with the given number of rooms in the garage
def __init__(self, maxSize):
self.carQueue = CarQueue()
self.maxSize = maxSize
#add car to the list, when arrive
def arrive(self, car):
self.carQueue.enqueue(car)
#remove car from the list and record movements of other cars to the southern side, when depart
def depart(self, car):
position = self.carQueue.positionOf(car)
self.carQueue.remove(car)
self.carQueue.moveCarsFrom(position)
#check whether the garage is full or not
def isFull(self):
return self.carQueue.size()==self.maxSize
#create new garage which can hold up to 10 cars
garage = Garage(10)
#create new CarQueue to store waiting cars
waiting = CarQueue()
header = """
##############################################
PARKING GARAGE
##############################################
Welcome!
"""
help = """
you have to input your command and press enter.
[a/d] [LICENSE PLATE NUMBER], for car arrival or departure
a, arrival
d, departure
help, show instructions
exit, quit the programme
show, show the queues in the garage and the waiting line
"""
#display the header
print("{0}Instructions:{1}\nPlease enter the command...".format(header, help))
#infinity loop to get user inputs again and again
while True:
#get user command
command = raw_input("\nlaughs> ")
#excecuting general commands
if command=="exit":
print("Good bye!\n")
break
elif command=="help":
print(help)
continue
elif command=="show":
print("Garage {0}: {1}".format(garage.carQueue.size(), garage.carQueue.toString()))
print("Waiting line {0}: {1}".format(waiting.size(), waiting.toString()))
continue
#get seperately the action character ('a' or 'd') and the license plate number from the command
action = ""
licenseNum = ""
try:
action,licenseNum = command.split()
except:
#show error message for invalid inputs
print("Invalid input! Try again. Enter 'help' for instructions")