python calculate time problem in function - python

I'm trying to create a Parking Lot in OOP.
I got stuck in payment calculated.
The payment is only calculated in seconds, how can I make it hourly or part of it?
(Under function “VehicleLeaves” I calculated secondsDiff.seconds because if I change it to secondsDiff.hour the program will crash.)
My Code:
import datetime
class Cars:
def __init__(self, phone, car_type, plate):
self.__phone = phone
self.__car_type = car_type
self.__plate = plate
def __str__(self):
return f"Plate: {self.__plate}, Phone: {self.__phone}, Car Type: {self.__car_type}."
class ParkingLot:
def __init__(self, name, capacity=1):
''' return a ParkingLot object with name "name" '''
self.name = name
self.capacity = capacity
self.earnings = 0
self.rate = 15
self.carsAndEnterTime = {}
def SetCapacity(self, newCap):
''' change the capacity from the default 1 '''
if newCap < 1:
raise RuntimeError("Error: parking lot size cannot be less than 1")
self.capacity = newCap
def GetCapacity(self):
''' return parking lot capacity '''
return self.capacity
def GetEarnings(self):
''' return how much much parking has made '''
return self.earnings
def VehicleEnters(self, vehicle):
''' vehicle enters parking lot'''
# put car and its enter time in a dictionary
self.carsAndEnterTime[vehicle] = datetime.datetime.now()
if self.capacity == 0:
raise RuntimeError("Error: Parking lot full!")
self.capacity -= 1
def VehicleLeaves(self, vehicle):
''' vehicle leaves parking lot. when it leaves, charges money '''
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
self.earnings += self.rate * secondsDiff.seconds
# after earned money, delete vehicle from dictionary
del self.carsAndEnterTime[vehicle]
self.capacity += 1
def __str__(self):
''' prints basic information of parking lot '''
return f"Parking lot: {self.name} \nSpots open: {self.capacity} \nHourly rate:{self.rate}\n {self.carsAndEnterTime}\nEarnings: $ {self.earnings} "
Focus on the area in the code of time calculation:
def VehicleEnters(self, vehicle):
''' vehicle enters parking lot'''
# put car and its enter time in a dictionary
self.carsAndEnterTime[vehicle] = datetime.datetime.now()
def VehicleLeaves(self, vehicle):
''' vehicle leaves parking lot. when it leaves, charges money '''
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
self.earnings += self.rate * secondsDiff.seconds
# after earned money, delete vehicle from dictionary
del self.carsAndEnterTime[vehicle]
self.capacity += 1
result in seconds, for this example is 10 seconds:
Earnings: $ 150
How can I calculate instead of seconds in hours or part of an hour rate of 15$.
For example, an hour and a half equals to 30$
what i did worng?

You can do a roundup withceil of math module:
import math
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
hour_roundup = math.ceil(secondsDiff.seconds/3600)

Related

Product Inventory program that takes products with an ID, quantity, and price and uses an Inventory class to keep track of the products

The Product class seems to work fine but I'm trying to figure out how to get the Inventory class to separate each product into there specific categories. I feel like I'm close but whenever I try and print out the inventory it just shows where it's stored in memory and doesn't actually print anything out. The output i receive when running is at the bottom. I want it to print out the actual products and data, not the instance of it stored in memory.
class Product:
def __init__(self, pid, price, quantity):
self.pid = pid
self.price = price
self.quantity = quantity
def __str__(self):
#Return the strinf representing the product
return "Product ID: {}\t Price: {}\t Quantity: {}\n".format(self.pid, self.price, self.quantity)
def get_id(self):
#returns id
return self.pid
def get_price(self):
#returns price
return self.price
def get_quantity(self):
#returns quantity
return self.quantity
def increase_quantity(self):
self.quantity += 1
def decrease_quantity(self):
self.quantity -= 1
def get_value(self):
value = self.quantity * self.price
return 'value is {}'.format(value)
product_1 = Product('fishing', 20, 10)
product_2 = Product('apparel', 35, 20)
class Inventory:
def __init__(self, products):
self.products = products
self.fishing_list = []
self.apparel_list = []
self.value = 0
def __repr__(self):
return "Inventory(products: {}, fishing_list: {}, apparel_list: {}, value: {})".format(self.products, self.fishing_list, self.apparel_list, self.value)
def add_fishing(self):
for product in self.products:
if product.get_id() == 'fishing':
self.fishing_list.append(product)
return '{} is in the fishing section'.format(self.fishing_list)
def add_apparel(self):
for product in self.products:
if product.get_id() == 'apparel':
self.apparel_list.append(product)
return '{} is in the apparel section'.format(self.apparel_list)
inventory_1 = Inventory([product_1, product_2])
inventory_1.add_fishing()
print(inventory_1)
OUTPUT = Inventory(products: [<main.Product instance at 0x10dbc8248>, <main.Product instance at 0x10dbc8290>], fishing_list: [<main.Product instance at 0x10dbc8248>], apparel_list: [], value: 0)
You need to specify how an object of the class Inventory should be printed.
To do this you need to implement at least one of the following functions in your class.
__repr__
__str__
This answer helps, which of both you should use: https://stackoverflow.com/a/2626364/8411228
An implementation could look something like this:
class Inventory:
# your code ...
def __repr__(self):
return str(self.products) + str(self.fishing_list) + str(self.apparel_list) + str(self.value)
# or even better with formatting
def __repr__(self):
return f"Inventory(products: {self.products}, fishing_list: {self.fishing_list}, apparel_list: {self.apparel_list}, value: {self.value})
Note that I used in the second example f strings, to format the output string.

Countdown with Python and Gtk, problems with timeout_add

I'm trying to make a workout app, so I have to count each push-up or display a countdown for side plank. To do that I tried to use GObject.timeout_add but it appears it doesn't work like I thought it would.
In the current situation, all exercises of a session are run simultaneously, instead of one at a time, in the proper order.
I am certainly missing something, and through my web searching, I still haven't found it.
Here is my code :
#!/usr/bin/python
"""
Work out app to keep track of your progression through the session
"""
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
from Programms import *
from time import sleep
def time_hours(t):
return t // 3600
def time_minutes(t):
return (t % 3600) // 60
def time_seconds(t):
return int((t % 3600) % 60)
def time_format(t):
hours = double_digit(time_hours(t))
minutes = double_digit(time_minutes(t))
seconds = double_digit(time_seconds(t))
return "{}:{}:{}".format(hours, minutes, seconds)
def double_digit(t):
if t == 0:
return "00"
elif t < 10:
return "0{}".format(t)
return t
class StartingLine:
"""
Gtk
"""
def __init__(self):
# main window
self.window = Gtk.Window()
self.window.set_title("Work out !")
self.window.set_size_request(200, 200)
self.window.connect('destroy', lambda x: Gtk.main_quit())
# start button
self.button = Gtk.Button("Start")
self.button.connect('clicked', self.start_work_out)
self.window.add(self.button)
self.window.show_all()
def start_work_out(self, widget):
self.window.hide()
work = Two
duration = work.duration
for exo in work.exercises:
Instructor(exo, duration)
class Instructor:
"""
Gtk
"""
def __init__(self, exo, duration):
# main window
self.window = Gtk.Window()
self.window.set_title("Work out !")
self.window.set_size_request(200, 200)
self.window.connect("destroy", lambda x: Gtk.main_quit())
# timer
self.current_time = 0
self.counter = 0
self.timer_label = Gtk.Label(time_format(self.counter))
# exercise
self.current_exercise = Gtk.Label(exo.name)
# overall progression
self.bar = Gtk.ProgressBar.new()
# hierarchy
grid = Gtk.Grid()
grid.attach(self.timer_label, 1, 0, 1, 1)
grid.attach(self.current_exercise, 1, 1, 1, 1)
grid.attach(self.bar, 1, 2, 1, 1)
self.window.add(grid)
# display
self.window.show_all()
if exo.type == ExoType.Reps:
print('exercise : ', exo.name)
self.counter = 0
self.timer_label.set_label(str(self.counter))
rep_id = GObject.timeout_add(1000*exo.in_between, self.display_rep, exo, duration)
print("rep ID : ", rep_id)
elif exo.type == ExoType.Timer:
self.counter = exo.number
self.timer_label.set_label(time_format(self.counter))
time_id = GObject.timeout_add(1000*exo.in_between, self.display_timer, exo, duration)
print("time ID : ", time_id)
def display_rep(self, exo, duration):
print("current time : ", self.current_time)
print("current exercise : ", exo.name)
print("rep : ", self.counter)
self.counter += 1
self.current_time += exo.in_between
self.timer_label.set_label(str(self.counter)) # update counter
self.current_exercise.set_label(exo.name) # update exercise name
self.bar.set_fraction(self.current_time/duration) # update progression bar
return self.counter < exo.number
def display_timer(self, exo, duration):
print("current time : ", self.current_time)
print("current exercise : ", exo.name)
print("timer : ", self.counter)
self.counter -= 1
self.current_time += exo.in_between
self.timer_label.set_label(time_format(self.counter)) # update counter
self.current_exercise.set_label(exo.name) # update name
self.bar.set_fraction(self.current_time/duration) # update progression bar
return self.counter > 0
if __name__ == "__main__":
StartingLine()
Gtk.main()
In this code I have used two types, which are :
#!/usr/bin/python
"""
define class exercise and class session
"""
class Exercise:
def __init__(self, name, typo, unilateral, number, preparation=0, in_between=1):
"""
:param name: name of the exercise
:param typo: either timer or reps
:param number: either a time in seconds or a a number of reps
:param preparation: time allocated to prepare the exercise, to put yourself in position
:param in_between: time between reps. 1s by default.
"""
self.name = name
self.type = typo
self.unilateral = unilateral
self.number = number
self.prep = preparation
self.in_between = in_between
class ExoType(enumerate):
Reps = 0
Timer = 1
class Session:
def __init__(self, name, exercises):
self.name = name
self.exercises = exercises
self.duration = time_length(exercises)
def time_length(exercises):
t = 0
for exo in exercises:
if exo.type == ExoType.Timer:
t += exo.number
elif exo.type == ExoType.Reps:
t += exo.number*exo.in_between
else:
print("Error : Session duration")
return t
First time I ask a question here, please tell me if I'm doing wrong.
rep_id = GObject.timeout_add(1000*exo.in_between, self.display_rep, exo, duration)
When you timeout_add you tell Mainloop to call function every n seconds.
for exo in work.exercises:
Instructor(exo, duration)
Here you add every exercise to mainloop, which leads to simultaneous run, because you create mainloop once.
There are several solutions and in my opinion none of them includes main_iteration_do.
Reorganise things so that 1 exercise runs it's own mainloop.
Emit a signal when one exercise is finished and in it's handler start another exercise.

Python test andela

HST2: OBJECT ORIENTED PROGRAMMING LAB
Create a class called ShoppingCart.
Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items.
Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item.
Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly.
If the quantity of an item to be removed exceeds the current quantity of that item in the cart, assume that all entries of that item are to be removed.
Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough".
Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100.
Make sure Shop inherits from ShoppingCart.
In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one.
# OOP Lab
class ShoppingCart(object):
def __init__(self):
total = 0
item = {}
self.total = total
self.item = item
def add_item(item_name, quantity, price):
cost = quantity * price
self.total += cost
self.item = {"item_name":quantity}
def remove_item(item_name,quantity,price):
cost = quantity * cost
self.total -= cost
for i in self.item:
if quantity > self.item[i]:
del self.item["item_name"]
def checkout(cash_paid):
if cash_paid < self.total:
return "Cash paid not enough"
class Shop(ShoppingCart):
def __init__(self):
quantity = 100
self.quantity = quantity
def remove_item():
self.quantity -= 1
#! Error State the following:
my add_item is having four argument instead of three each time i run this code:
Please i need help with this code, am new with python, i will appreciate any programming angel in python to rescue me now.
Try this, it should work out just fine:
class ShoppingCart(object):
def __init__(self):
self.total = 0
self.items = {}
def add_item(self, item_name, quantity, price):
self.total += quantity * price
if type(item_name) == str and quantity > 0:
self.items.update({item_name: quantity})
def remove_item(self, item_name, quantity, price):
if quantity >= self.items[item_name] and quantity >= 1:
items_cost = price * self.items[item_name]
self.total -= items_cost
del self.items[item_name]
else:
self.total -= quantity * price
self.items[item_name] -= quantity
def checkout(self, cash_paid):
balance = 0
if cash_paid < self.total:
return "Cash paid not enough"
balance = cash_paid - self.total
return balance
class Shop(ShoppingCart):
def __init__(self):
self.quantity = 100
def remove_item(self):
self.quantity -= 1
Class methods should accept self as the first argument so for example
def add_item(self, item_name, quantity, price):
Instead of
def add_item(item_name, quantity, price):
The "4th argument" being passed is implicitly self, that is why the number of arguments is one higher than you are expecting.

Code about car park

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")

Passing arguments through a class in python

I have to call the "accelerate" method 5 times and display it's output after each iteration. The same must be done with the "brake" method. I have all of this written, but I'm at a loss in where to even begin to call the method in the main function to achieve my desired goal. Any help is greatly appreciated!! I'm in Python 3.3
class Car:
def __init__(self):
self.__year_model = 0
self.__make = ''
self.__speed = 0
def set_year_model(self, year):
self.__year_model = year
def set_make(self, make):
self.__make = make
def set_speed(self, speed):
self.__speed = speed
def accelerate(self):
return self.__speed + 5
def brake(self):
return self.__speed - 5
def get_year_model(self):
return self.__year_model
def get_make(self):
return self.__make
def get_speed(self):
return self.__speed
def main():
mycar = Car()
year = input('Enter the year of the vehicle: ')
make = input('Enter the make of the vehicle: ')
speed = input("Enter the vehicle's current speed: ")
mycar.set_year_model(year)
mycar.set_make(make)
mycar.set_speed(speed)
accel = mycar.accelerate()
brake = mycar.brake()
main()
Your accelerate code is wrong: the changed speed is never stored. It should be
def accelerate(self):
self.__speed += 5
and similarly for brake.
Edit: getter and setter methods aren't really idiomatic Python. You probably want
class Car:
def __init__(self, year, make, speed=0):
self.year = year
self.make = make
self.speed = speed
def accelerate(self, amount=5):
self.speed += amount
def brake(self, amount=5):
self.speed -= amount
def main():
year = input('Enter the year of the vehicle: ')
make = input('Enter the make of the vehicle: ')
speed = input("Enter the vehicle's current speed: ")
mycar = Car(year, make, int(speed))
print("Accelerating:")
for _ in range(5):
mycar.accelerate()
print(mycar.speed)
print("Braking:")
for _ in range(5):
mycar.brake()
print(mycar.speed)
if __name__=="__main__":
main()
which gives
Enter the year of the vehicle: 1990
Enter the make of the vehicle: Corolla
Enter the vehicle's current speed: 20
Accelerating:
25
30
35
40
45
Braking:
40
35
30
25
20
This would be solved by a simple looping structure. In your main method, try:
for item in range(0,5):
accel = mycar.accelerate()
print(accel)
Edit: Please note that this is probably not the best way to do this, but the first way that came to mind. In regards to the int/str conversion, you might just want to cast. I typically use Python 2.7.x and couldn't remember if you needed to cast to string for Python 3.0's print function.

Categories

Resources