I'm learning python here:
I have created this cars class below and I want to that result go to the list.
What is the most efficiency way to do it?
class Car:
def __init__(self, brand="", price=""):
self.brand = brand
self.price = price
def __str__(self):
return str(self.brand) + " " + str(self.price)
import random
carslist = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
car1 = Car()
car1.brand = (random.choice(carslist))
car1.price = (random.randint(1000, 10000))
car2 = Car()
car2.brand = (random.choice(carslist))
car2.price = (random.randint(1000, 10000))
car3 = Car()
car3.brand = (random.choice(carslist))
car3.price = (random.randint(1000, 10000))
car4 = Car()
car4.brand = (random.choice(carslist))
car4.price = (random.randint(1000, 10000))
car5 = Car()
car5.brand = (random.choice(carslist))
car5.price = (random.randint(1000, 10000))
print(car1)
I did try it like this cars1 = car1details cars2 = car2details and list [car1details, car2details] but that's not probably the best way to do it.
Thanks for you help!
The below seems to work nice (__repr__ was added since when we print the cars it is used)
import random
class Car:
def __init__(self, brand="", price=0):
self.brand = brand
self.price = price
def __str__(self):
return str(self.brand) + " " + str(self.price)
def __repr__(self):
return str(self.brand) + " " + str(self.price)
cars_models = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
cars = [Car(random.choice(cars_models),random.randint(1000, 10000)) for _ in range(1,8)]
print(cars)
output
[BMW 2008, Volvo 3810, Skoda 8545, Skoda 6715, Ford 9792, Audi 6013, VW 1475]
here is an example of how to append objects to a list by using range()
When you append the Car object you can add variables
class Car(object):
def __init__(self, number):
self.number = number
my_objects = []
for i in range(100):
my_objects.append(Car(i))
from random import randint
class Car():
def __init__(self, name):
self.name= name
self.price = randint(1000, 10000)
def __str__(self):
return f'Car( Name: {self.name} | price {self.price})'
def __repr__(self):
return f'Car( Name: {self.name} | price {self.price})'
carsname = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
cars = []
for name in carsname:
cars.append(Car(name))
Use a basic for :)
Related
Trying to generate school timetable with lab hours.
Kindly help me to solve this error! Thanks in advance.
Here is my code!
#planning_solution
class TimeTable:
timeslot_list: list[Timeslot]
timeslot_list1: list[Timeslot]
room_list: list[Room]
lesson_list: list[Lesson]
lab_list: list[Lab]
score: HardSoftScore
def __init__(self, timeslot_list, timeslot_list1, room_list, lesson_list,lab_list,
score=None):
self.timeslot_list = timeslot_list
self.timeslot_list1 = timeslot_list1
self.room_list = room_list
self.lesson_list = lesson_list
self.lab_list = lab_list
self.score = score
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLS")
def get_timeslot_list(self):
return self.timeslot_list
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLB")
def get_timeslot_list1(self):
return self.timeslot_list1
#problem_fact_collection_property(Room)
#value_range_provider("roomRange")
def get_room_list(self):
return self.room_list
#planning_entity_collection_property(Lesson)
def get_lesson_list(self):
return self.lesson_list
#planning_entity_collection_property(Lab)
def get_lab_list(self):
return self.Lab_list
#planning_score(HardSoftScore)
def get_score(self):
return self.score
def set_score(self, score):
self.score = score
def __str__(self):
return (
f"TimeTable("
f"timeslot_list={format_list(self.timeslot_list)},\n"
f"timeslot_list1={format_list(self.timeslot_list1)},\n"
f"room_list={format_list(self.room_list)},\n"
f"lesson_list={format_list(self.lesson_list)},\n"
f"lab_list={format_list(self.lab_list)},\n"
f"score={str(self.score.toString()) if self.score is not None else 'None'}"
f")"
)
Trying to get the 2 timeslots one for lesson(1 hour) and one for lab(2 hour).Here is my #planning_solution.
I defined 2 #planning_entity for both lab & lesson with #value_range_provider.
#planning_entity
class Lab(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot1: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot1 = None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot1 = timeslot1
self.room = room
#planning_variable(Base, value_range_provider_refs=['roomRange', 'timeslotRangeLB'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLB"])
def get_timeslot1(self):
return self.timeslot1
#value_range_provider(range_id = "timeslotRangeLB", value_range_type = Timeslot)
def get_possible_timeslot_list1(self):
return self.subject.teacher.student_group.room_list
def set_timeslot1(self, new_timeslot):
self.timeslot1 = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lab("
f"id={self.id}, "
f"timeslot1={self.timeslot1}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
#planning_entity
class Lesson(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot=None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot = timeslot
self.room = room
#planning_variable(Base, value_range_provider_refs=['timeslotRangeLS', 'roomRange'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLS"])
def get_timeslot(self):
return self.timeslot
#value_range_provider(range_id = "timeslotRangeLS", value_range_type = Timeslot)
def get_possible_timeslot_list(self):
return self.subject.teacher.student_group.room_list
# return self.course.teacher.department.room_list
def set_timeslot(self, new_timeslot):
self.timeslot = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lesson("
f"id={self.id}, "
f"timeslot={self.timeslot}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
The issue is you defined #value_range_provider(range_id = "timeslotRangeLS") on both your #planning_solution and your #planning_entity. You can only have one; if you want the value range to apply to every entity, do it on the #planning_solution. If you want each planning entity to have it own value range that only applies to it, do it on the #planning_entity. If you want to combine a value range that contains common values for all entities, and a value range that is per entity, use a #value_range_provider on the #planning_solution, and a #value_range_provider on the entity, but give them different ids (ex: #value_range_provider(range_id = "timeslotRangeLSSolution") and #value_range_provider(range_id = "timeslotRangeLSEntity"), and in the #planning_variable, use both range ids in the list (ex: #planning_variable(Room, ["timeslotRangeLSSolution", "timeslotRangeLSEntity"])
I have made this code and now I want to add from the class 'Product' the price together. So I have 2 products: Computer and Nintendo and I want to add the price together, can I make a definition for this so that from product 3 and 4 it will also add up?
I hope my question makes sense, I'm a beginner in programming.
class Customer:
def __init__(self, ID, name, address):
self.ID = ID
self.name = name
self.address = address
def customer_information(self):
print('ID: '+ self.ID + ', Name: ' + self.name + ', Address: '+ self.address)
class Product:
def __init__(self, product_name, product_ID, price):
self.product_name = product_name
self.product_ID = product_ID
self.price = price
def product_information(self):
print(self.product_name+', '+self.product_ID + ', €'+str(self.price))
class Order:
def __init__(self):
self.customer = []
self.product = []
def add1(self, product):
self.product.append(product)
def customer_data(self, customer):
self.customer.append(customer)
def show(self):
for c in self.customer:
c.customer_information()
print('This order contains:')
for p in self.product:
p.product_information()
customer1 = Customer('542541', 'Name', 'Rotterdam')
customer2 = Customer('445412', 'Name', 'Schiedam')
product1 = Product('Computer', '34456', 200.00)
product2 = Product('Nintendo', '12345', 14.99)
product3 = Product('Camera', '51254', 50.00)
product4 = Product('Go-pro', '51251', 215.00)
myOrder = Order()
myOrder.customer_data(customer1)
myOrder.add1(product1)
myOrder.add1(product2)
myOrder1 = Order()
myOrder1.customer_data(customer2)
myOrder1.add1(product3)
myOrder1.add1(product4)
myOrder.show()
myOrder1.show()
Seems like you want to get the sum of all the product prices, or order totals. Both are the same result, but you have two classes that contain the same information so you can calculate the sums by either Product or Order:
productsum = product1.price + product2.price + product3.price + product4.price
ordersum = sum([p.price for p in myOrder.product]) + sum([p.price for p in myOrder1.product])
print(productsum) # 479.99
print(ordersum) # 479.99
Either way you'll get the same answer, just choose how you want to implement it.
Yes, you can create another variable in class order like-
def __init__(self):
self.customer = []
self.product = []
self.total = 0
and add every product's price to the total whenever a product is added to the list-
def add1(self, product):
self.product.append(product)
self.total += product.price
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
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".
Alright so I have a dict with keys that point to an array of 5 values. These 5 values I pass to a class to sort out and feed me info etc.
Main
So, this works, but my querstion is is there a better way of exytracting the array to pass to the 'weapon' class, or do i just need to 'wepstats[0],wepstats[1]' etc? Or is there a better way of going about this? I'm all ears as Im only learning to do this stuff.
class Main():
def weaponDamage(self):
#print 15 * 2.22
wdb = WeaponDB()
wepstats = wdb.getWeaponStats('Sword')
wep = Weapon(wepstats[0],wepstats[1],wepstats[2],wepstats[3],wepstats[4])
wep2 = Weapon("Sword", 5, 55, 1.55, 2.1)
print wep
print wep2
s = sayThings()
greet = s.Say()
self.crit = wep.getDamageCrtRND()
self.scrit = wep.getDamageSCrtRND()
self.avg = wep.getDamageAvg()
self.high = wep.getDamageHigh()
self.low = wep.getDamageLow()
self.mod = wep.getDamageMod()
self.norm = wep.getDamageNrmRND()
self.name = wep.getWeaponName()
print greet
print "-----------"
print "Name: " + self.name
print "-----------"
print "High: %s" % self.high
print "Low : %s" % self.low
print "Avg : %s" % self.avg
print "Crit: %s" % self.crit
print "--------------------"
Dict
EDIT: Should I be making a DB of items in this manner in the first place? Is there a more logic method of doing this?
class WeaponDB():
"""Here be thine weapons of thy holy might"""
def __init__(self):
self.script = {
'None': "Error: No Weapon stats to get selected.",
'Sword': ("Sword", 5, 55, 1.55, 2.1),
}
def getWeaponStats(self, key = 'None'):
try:
return self.script[key]
except KeyError:
return self.script['None']
Class useing the values as parameters
class Weapon():
def __init__(self, name = "Stick", high = 1, low = 0, critMod = 1, scritMod = 2):
self.rng = randNum()
self.name = name
self.high = high
self.low = low
self.critMod = critMod
self.scritMod = scritMod
def getWeaponName(self):
return self.name
def getDamageHigh(self):
return self.high
def getDamageLow(self):
return self.low
def getDamageMod(self):
return self.critMod
def getDamageSMod(self):
return self.scritMod
etc...
If I understand well you can do something like this:
class Weapon:
def __init__( self, name = 'Stick', high = 1, low = 0 ):
self.name = name
self.high = high
self.low = low
wepstats = ( 'Sword', 5, 55 )
sword = Weapon( *wepstats )
Then if you check your attributes you get:
>>> sword.name
'Sword'
>>> sword.high
5
>>> sword.low
55
Using *wepstats you pass the entire tuple as arguments for your constructor.