Python list with two values - python

I have a program that simulates a bus in the form of a list and there is an ability to add passengers to the bus. I want to be able to set a max number of passengers, so that if the list exceeds 25 passengers I display a code stating that the bus is full.
Is it possible to set this limit in a list with Python.
Here is a snippet of the code:
#defining a class for the passenger list
class Bus:
passengers = []
number_of_passengers = 0

You can use super keyword for override lists.
class PassengerList(list):
limit = 0
def __init__(self, lim):
self.limit = lim
def append(self, item):
if len(self) >= self.limit:
raise Exception('Limit exceeded.')
super(PassengerList, self).append(item)
passengers = PassengerList(25)
passengers.append('abc')
You can set limit by parameter.

You'd probably want to check the length of the list and then decide if you'll add a passenger or display a message. Something like so:
class Bus:
def __init__(self, max_number_of_passengers = 25):
self.passengers = []
self.max_number_of_passengers = max_number_of_passengers
def add_passenger(self, passenger):
if len(self.passengers) > self.max_number_of_passengers:
# display message
else:
self.passengers.append(passenger)

you can use a class
class Bus:
def __init__(self):
self.passengers = []
self.MAX_LIMIT = 25
def add_passenger(self, passenger):
if(len(self.passengers) <= self.MAX_LIMIT):
self.passengers.append(passenger)
else:
print('sorry bus is full')
def show_passengers(self):
print(self.passengers)
bus = Bus()
for i in range(26):
bus.add_passenger(i)
bus.add_passenger(26) #sorry bus is full

class Bus:
def __init__(self, limit=25):
self.passengers = []
self.bus_limit = limit
self.is_bus_full = False
def add_passenger(self):
if len(self.passengers) < self.bus_limit:
self.passengers.append(1) # add dummy values
else:
self.is_bus_full = True
def passenger_left(self):
self.passengers.pop()
def bus_status(self):
if self.is_bus_full:
return 'This bus is full'
else:
return 'This bus has vacant seats'
You can write something like this.

Related

Library Member class, can't figure out where I'm going wrong

I am trying to complete a series of class definition tasks and can't seem to get past this one. It is part of a 3 part series; the first part asks you to model a library book, which I could complete easily.
The next part is asking to create a Member class to model a library member and include a borrow_book() and a return_book() method, and to get the member's list of all loan books to print out in alphabetical order.
I cannot understand which part I am going wrong on. Could someone possibly point me in the right direction? I have included my code so far below.
class Book(object):
def __init__(self, title, author, copies=1, loan=0):
self.title = title
self.author = author
self.copies = copies
self.loan = loan
def checkbook(self, title):
for book in self.title:
if book.title in self.title:
return book
else:
print("Sorry, Not Available.")
def borrow_book(self):
abc = self.checkbook(title)
print(abc)
self.loan += 1
self.copies -= 1
def return_book(self):
self.loan -= 1
def __str__(self):
r = []
r.append('Title: {}'.format(self.title))
r.append('Author: {}'.format(self.author))
r.append('Copies: {}'.format(self.copies))
r.append('On loan: {}'.format(self.loan))
return '\n'.join(r)
def sort_books(b):
return b.title
class Member(object):
def __init__(self, mid, name, loans=0):
self.mid = mid
self.name = name
self.loans = loans
self.d = {}
def __str__(self, mid, name, loans=0):
r = []
r.append('ID: {}'.format(self.mid))
r.append('Name: {}'.format(self.name))
r.append('Loans: {}'.format(self.loans))
l = ['{}'.format(b) for b in sorted(self.d.values(), key=sort_books)]
return '\n'.join(r)
return '\n'.join(l)

Modify object attribute in Class declaration due to attributes relationship

I have a class with 3 attributes:
class Player():
def __init__(self,pos,stack):
self.pos = pos
self.stack = stack
self.debt = 0
All instances will begin with debt = 0. In my main program I will be modifying these attributes for many instances, but a player's debt can't be greater than a player's stack. Is it a way to prevent (especify) this from the class declaration? . I don't want to write
if player.debt > player.stack:
player.debt = player.stack
everytime a player's debt is modified. Is it a way to do this automatically from the class Player?
For example, in the following code I want to make the automatic modifications :
jug = Player("BTN",1000) # jug.debt then must be 0
jug.debt = 500 # jug.debt then must be 500
jug.debt = 2000 # jug.debt then must be 1000
Write a property and in the setter check if it exceeds the limit.
class Player():
def __init__(self,pos,stack):
self.pos = pos
self.stack = stack
self._debt = 0
#property
def debt(self):
return self._debt
#debt.setter
def debt(self, val):
if val > self.stack:
val = self.stack
self._debt = val

Python thread class instance change a variable for all instances

I'm new to python threads and I can't find any answers for that. If it is a duplicate question sorry for that.
I have a thread class like this:
class Ant(Thread):
def __init__(self, start_item, possible_items, backpack_limit, pheromone_map, alpha, beta, eta):
Thread.__init__(self)
self.start_item = start_item
self.item = start_item
self.possible_items = possible_items
self.selected_items = []
self.backpack_limit = backpack_limit
self.weight_sum = 0
self.backpack_value = 0
self.pheromone_map = pheromone_map
self.alpha = alpha
self.beta = beta
self.eta = eta # (weight/value)
# append start location to route, before doing random walk
self.add_backpack(start_item)
self.tour_complete = False
def run(self):
while self.possible_items and self.is_remaining_space_feasible():
next_item = self.pick_item()
self.item = next_item
self.add_backpack(next_item)
self.tour_complete = True
def add_backpack(self, next_item):
self.update_items(next_item)
self.update_backpack(next_item)
def update_items(self, next_item):
self.selected_items.append(next_item)
self.possible_items.remove(next_item)
def update_backpack(self, next_item):
self.weight_sum += next_item.get_weight()
self.backpack_value += next_item.get_value()
and I create bunch of instances in another class like this:
ants = [Ant(self.items[random.randint(0, len(self.items) - 1)], self.items, self.backpack_limit, self.pheromone_matrix, self.alpha, self.beta, self.eta) for _ in range(self.ant_count)]
As you can see when I create an ant instance it's called add_backpack function and at some point this piece of code work self.possible_items.remove(next_item) and the program finished the initialization step and create the next instance. But for the next instance possible_items already removed the item and this caused list.remove(x): x not in list error. I tried deep copying but it's doesn't work.

How to replace an integer with a different class when it is assigned

I have a class called newInteger, and a variable called num, but I would like num to be a newInteger() instead of an int(). Code below.
class newInteger(int):
def __init__(self, value):
self.value = value
num = 10
I want the line num = 10 to act as if it is num = newInteger(10). Thanks to anyone who can help me with this.
You can run a small thread parallel to your main program that replaces all created integers to newInteger:
import threading
import time
class newInteger(int):
def __init__(self, value):
self.value = value
def __str__(self):
return "newInteger " + str(self.value)
def replace_int():
while True:
g = list(globals().items())
for n, v in g:
if type(v) == int:
globals()[n] = newInteger(v)
threading.Thread(target=replace_int, daemon=True).start()
num = 10
time.sleep(1)
print(num)
But this is unpythonic and will be realy hard to debug. You should just use a explicit conversion like #johnashu proposed
I am not sure if this is what you mean but if youassign the class to a variabl. then it will be an instance of that class..
example:
class newInteger(int):
def __init__(self, value):
self.value = value
num = 10
if num == 10:
num = newInteger(10)
prints:
hello

How to query on a list by list comprehension and min/max functionalities

I have two Python classes: Agent and Group...
Each Group has a centerGroup property, plus a static list of groups, i.e. GroupList
Here is a brief overview of the Group class:
import Agent
class Group(object):
"""description of class"""
GroupIdentifier = 1
GroupThreshold = 10
GroupList = []
def __init__(self, agentList = None ,groupCenter = None, gruopIdentifier = None):
global GroupIdentifier
global GroupList
self.groupIdentifier = GroupIdentifier
Group.GroupIdentifier += 1
Group.GroupList.append(self)
self.groupCenter = groupCenter
self.agentList = agentList
Furthermore, within the Agent class, I am going to find the minimum euclidean distance of a typical agent from all centerGroup properties corresponding to the groups in the groupList... (There is an offset, is which GAMMA_TRESHOLD)...
One can depict the related part of Agent class, as below snippet:
import Group
class Agent(object):
"""description of class"""
GAMMA_TRESHOLD = 20
def __init__(self, point = None, groupId = None):
self.locationX = point.x
self.locationY = point.y
self.groupId = 0
def get_agent_distance_from_groupCenter(self, object):
return math.sqrt(math.pow(self.locationX - point.x, 2) +
math.pow(self.locationY - point.y, 2))
def gamma_condition(self):
#I KNOW THIS IMPLEMENTATION IS WRONG... JUST GOTTA SHOW THE TARGET!
return Group.Group.GroupList[Group.Group.GroupList.index(min(get_agent_distance_from_groupCenter(agent, group.groupCenter) - GAMMA_TRESHOLD))]
From a mathematical manner perspective, the problem is minimizing the below norm and introducing the group, which its centerGroup is nearest to the agent:
min \norm{centerGroup_{i} - agent - TRESHOLD}
Would you please helping me to write such query (valid processing for gamma_condition method) by list comprehension of Python?!
All in all, with due attention to lack of any better idea from the other people, my investigations lead to below solution for this problem:
def gamma_condition(self):
temp = []
maxValue = 0
temp = [[item.groupIdentifier, JOIN_TRESHOLD - self.get_agent_distance_from_groupCenter(item.groupCenter)] for item in Group.Group.GroupList]
for item in temp:
maxValue = max(float(i) for i in item[1])
if maxValue > 0:
index = temp.index(maxValue)
NearestGroupIdToJoin = temp[index][0]
return NearestGroupIdToJoin
else:
return None

Categories