Including another object inside an object and calling a specific value - python

I'm trying to make a simple 5v5 sport management, but I'm not sure how can I link players to teams, in order to make the overall rating of the team be the sum of the players rating / amount of players. Unfortunately my current code only returns where the object is ( <main.Player object at 0x000001CED897FCD0>) but not the player at all, so of course the overall is off
class Player:
totalPlayers = 0
def __init__(self,PName, PYearBorn, POvr, PNumber, PIndex):
self.PName = PName
self.PYearBorn = PYearBorn
self.POvr = POvr
self.PNumber = PNumber
self.PIndex = PIndex
Player.totalPlayers += 1
def getPlayer(self):
return self.PName, self.PYearBorn, self.POvr, self.PNumber, self.PIndex
'''
Player Name
Year Born
Player Overall
Player Number
Player Index'''
class HistoricPlayer(Player):
def __init__(self,PName, PlayerAge, POvr, PNumber, PIndex):
self.PlayerAge=PlayerAge
Player.__init__(self,PName, PlayerAge, POvr, PNumber, PIndex,)
class Franchise():
totalFranchises = 0
def __init__(self, FName, region, championships, yearCreated, rivals):
self.FName = FName
self.region = region
self.championships = championships
self.yearCreated = yearCreated
self.rivals = rivals
Franchise.totalFranchises += 1
class Team(Franchise):
totalTeams = 0
def __init__(self, TName, FName, amountofplayers, maxplayercapacity, region, championships, yearCreated, rivals, currentplayers):
Franchise.__init__(self, FName, region, championships, yearCreated, currentplayers)
self.currentplayers = currentplayers
self.overall = currentplayers[1].POvr/amountofplayers
self.rivals = rivals
self.TName = TName
self.amountofplayers = amountofplayers
self.maxplayercapacity = maxplayercapacity
self.currentplayers = currentplayers
Team.totalTeams+=1
def getTeam(self):
return self.TName, self.FName, self.amountofplayers, self.maxplayercapacity, self.region, self.championships, self.yearCreated, self.rivals, self.currentplayers
''' #Team Class Values
Team Name
Franchise Name
Overall
Amount of current players
Maximum player capacity
Team Region
Championships
Year of Creation
Rivals
Current Players
'''
P01=Player('Francis', 2000, 8, 69, 'p01')
P02=Player('Franton', 2000, 8, 69, 'p01')
P03=Player('Frank', 2000, 8, 69, 'p01')
P04=Player('Felitio', 2000, 8, 69, 'p01')
P05=Player('Fred', 2000, 8, 69, 'p01')
T01=Team('5 Friends', "The friends' club", 5, 6, "Hometown", 0, 2022, 'Rich', (P01, P02, P03, P04, P05))
print(T01.getTeam())
Any idea what should or can I do/what am I doing wrong?

Related

How to make a simple family budget calculator

I am making a simple budget calculator and It is a little bit complicated for me as a beginner. I need to add elements to a list through a function and then print an overview of a specific month and a year. It should sum up the money in each category and print it out.
budget=[]
def add_element (day,month,year,money,category):
budget.append(day,month,year,money,category)
def overview (month,year):
add_element(15,10,2022,150,"food")
add_element(16,11,2022,250,"food")
add_element(17,11,2022,300,"living")
add_element(18,11,2022,500,"food")
add_element(19,11,2022,150,"household")
print(overview(11,2022))
I am expecting this outcome:
{"food": 750, "household": 150, "living": 300}
Similar with using defaultdict
from collections import defaultdict
budget = []
def add_element(*row):
budget.append(row)
def overview(month, year):
summary = defaultdict(int)
for d, m, y, money, category in budget:
if m == month and y == year:
summary[category] += money
return summary
add_element(15, 10, 2022, 150, "food")
add_element(16, 11, 2022, 250, "food")
add_element(17, 11, 2022, 300, "living")
add_element(18, 11, 2022, 500, "food")
add_element(19, 11, 2022, 150, "household")
print(overview(11, 2022)) # defaultdict(<class 'int'>, {"food": 750, "household": 150, "living": 300})
you can anytime convert to dict using dict(summary)
The below code should help you with your need.
def add_element(day, month, year, money, category):
budget.append([day, month, year, money, category])
def overview(month, year):
food_total = 0
household_total = 0
living_total = 0
for item in budget:
if item[1] == month and item[2] == year:
if item[4] == "food":
food_total += item[3]
elif item[4] == "household":
household_total += item[3]
elif item[4] == "living":
living_total += item[3]
return {"food": food_total, "household": household_total, "living": living_total}
budget = []
add_element(15,10,2022,150,"food")
add_element(16,11,2022,250,"food")
add_element(17,11,2022,300,"living")
add_element(18,11,2022,500,"food")
add_element(19,11,2022,150,"household")
print(overview(11,2022))

How to create class diagram and write pseudocode that defines the class?

I want to design a class named houses that holds the street address, asking price, number of bedrooms and number of bathrooms in the house. I would also like methods included to get and set values for each data field.
First time working with classes.
I got the class setup and I'm able to print the classes but I'm not sure how or which methods to use.
class houses:
def __init__(self, Adress, Askingprice, NumOfBedrooms, NumofBathroom):
self.Adress = Adress
self.Askingprice = Askingprice
self.NumOfBedrooms = NumOfBedrooms
self.NumofBathroom = NumofBathroom
def HouseDetails(self):
return "The house is at {} with a price of {} and has {} Bedroom/s and {} bathroom/s" \
.format(self.Adress, self.Askingprice, self.NumOfBedrooms, self.NumofBathroom)
house1 = houses("Almonaster_Avenue87", "R 500k", 1, 1)
house2 = houses("Audubon_Place33", "R 900k", 3, 3)
house3 = houses("Baronne_Street78", "R800k", 3, 2)
house4 = houses("Basin_Street55", "R700k", 2, 1)
house5 = houses("Bayou_Road11", "R 900", 4, 2)
house6 = houses("Bienville_Street78", "R700k", 2, 2)
house7 = houses("Bourbon_Street45", "R 800k", 4, 1)
house8 = houses("Broad_Street56", "R 900k", 5, 3)
print("\n",house1.HouseDetails())
Please Note
The "R" at asking price is my currency.
If you must have getter and setter methods, here's a succinct way to do it using Python's built-in property class. The create_property() utility function shown is a simplified version of recipe 9.21 in the 3rd edition of the Python Cookbook by Beazley & Jones (2013).
def create_property(name):
""" Utility to define repetitive property methods. """
storage_name = '_' + name
#property
def prop(self): # getter
return getattr(self, storage_name)
#prop.setter
def prop(self, value): # setter
return setattr(self, storage_name, value)
return prop
class House:
address = create_property('address')
asking_price = create_property('asking_price')
num_bedrooms = create_property('num_bedrooms')
num_bathrooms = create_property('num_bathrooms')
def __init__(self, address, asking_price, num_bedrooms, num_bathrooms):
self.address = address
self.asking_price = asking_price
self.num_bedrooms = num_bedrooms
self.num_bathrooms = num_bathrooms
def __str__(self):
return("The house is at {} with a price of {} and has "
"{} Bedroom/s and {} bathroom/s".format(self.address,
self.asking_price, self.num_bedrooms,
self.num_bathrooms))
house1 = House("Almonaster Avenue 87", "R 500k", 1, 1)
house2 = House("Audubon Place 33", "R 900k", 3, 3)
house3 = House("Baronne Street 78", "R 800k", 3, 2)
house4 = House("Basin Street 55", "R 700k", 2, 1)
house5 = House("Bayou Road1 1", "R 900", 4, 2)
house6 = House("Bienville Street 78", "R 700k", 2, 2)
house7 = House("Bourbon Street 45", "R 800k", 4, 1)
house8 = House("Broad Street 56", "R 900k", 5, 3)
print(house1)
Output:
The house is at Almonaster Avenue 87 with a price of R 500k and has 1 Bedroom/s and 1 bathroom/s

Python Class File to List

So I'm doing a project that I have to create a class that going to read information in a file like the one below, and put it in a list.
Each value in the list have to assign to a variable (name = 'Guillaume Dutroux')
Day: 2019-01-12
Time:
09:00
Company:
iCageDoree
Clients:
Guillaume Dutroux, london, 2019-03-12, 13:30, 55, 4*, plumbing, 4h00
Jose Quesada, madrid, 2019-03-12, 10:00, 30, 2*, refrigerators, 5h15
Martin Wyne, london, 2019-04-30, 19:45, 105, 3*, wifi, 0h30
class ReadClients:
def __init__(self, fileClients):
self._fileClients = fileClients
def readClients(self):
with open(self._fileClients, "r") as file:
for i in range(7):
file.readline()
self._clientsData = []
for line in file:
name, city, date, time, maxValue, minRep, domain, timeWork = line.strip(" ").split(",")
self._clientsData.append(Clients(name, city, date, time, maxValue, minRep, domain, timeWork))
self._nameCl = name
self._cityCl = city
self._dateCl = date
self._timeCl = time
self._maxValueCl = maxValue
self._minRepCl = minRep
self._domainCl = domain
self._timeWorkCl = timeWork
return self._clientsData
My code above is returning me:
[<clients.Clients object at 0x01B77170>, <clients.Clients object at 0x01B77230>, <clients.Clients object at 0x01B77310>]
and I don't know why.
Hope you can Help me.
Here is a small example of how you can play around with __repr__
class my_class:
def __init__(self,name,age):
self.name=name
self.age=age
def __repr__(self):
return "(name="+self.name+', '+"age"+str(self.age)+")"
my_list = [my_class('a',1),my_class('a',2)] # [(name=a, age1), (name=a, age2)]

Python script error sqlite3.OperationalError: no such column:

I get this error when I run the script and I cannot see the solution. This program is supposed to draw a giveaway from a sqlite3 file which has the number of raffle tickets for a user. And recently the program the gives that creates the sqlite3 file updated some stuff (The script is made by me) and I can figure out the solution.
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Draw\Test\dave-draw.py", line 244, in <module>
dd = DaveDraw()
File "C:\Users\Admin\Desktop\Draw\Test\dave-draw.py", line 64, in __init__
self.get_viewers()
File "C:\Users\Admin\Desktop\Draw\Test\dave-draw.py", line 215, in
get_viewers
''').fetchall()
sqlite3.OperationalError: no such column: viewer_id
there's the code
#!/usr/bin/env python3
import pdb
import random
import sqlite3
class Viewer(object):
def __init__(self,
viewer_id,
twitch_name,
beam_name,
beam_id,
viewer_type,
rank,
points,
points2,
hours,
raids,
gains_currency,
gains_hours,
in_giveaways,
last_seen,
sub,
entrance_message,
entrance_message_type,
entrance_sfx
):
self.viewer_id = viewer_id
self.twitch_name = twitch_name
self.beam_name = beam_name
self.beam_id = beam_id
self.viewer_type = viewer_type
self.rank = rank
self.points = points
self.points2 = points2
self.hours = hours
self.raids = raids
self.gains_currency = gains_currency
self.gains_hours = gains_hours
self.in_giveaways = in_giveaways
self.last_seen = last_seen
self.sub = sub
self.entrance_message = entrance_message
self.entrance_message_type = entrance_message_type
self.entrance_sfx = entrance_sfx
def win_chance(self, total_tickets):
"""
Takes the total tickets (points) as a paramter and works
out the percentage chance that the viewer has of winning.
Returns the viewers win chance in percent.
"""
percent = total_tickets / 100.00
return self.points2 / percent
class DaveDraw(object):
def __init__(self):
self.debug = False
self.database_path = 'Viewers3DB.sqlite'
self.db_conn = sqlite3.connect(self.database_path)
self.get_viewers()
self.calculate_total_points()
self.assign_tickets()
def assign_tickets(self):
"""
Assigns each user a number range based on the number of
tickets they have.
e.g.
10 1-10
10 11-20
30 21-50
1 51
"""
self.tickets = {}
latest_ticket = 0
for viewer in self.viewers:
# skip anyone with no points
if viewer.points2 == 0:
continue
ticket_range_beg = latest_ticket + 1
ticket_range_end = latest_ticket + 1 + viewer.points2
latest_ticket = ticket_range_end
viewer.tickets = range(ticket_range_beg, ticket_range_end)
# assign a range of tickets:
if self.debug:
print("Assigning viewer twitch: %s beam: %s tickets %i-%i" % (viewer.twitch_name, viewer.beam_name, viewer.tickets.start, viewer.tickets.stop))
if ticket_range_beg == ticket_range_end:
if self.debug:
print("Assigning ticket {} to {}".format(ticket_range_beg, viewer.twitch_name))
self.tickets[ticket_range_beg] = viewer
next
for ticket in viewer.tickets:
if self.debug:
print("Assigning ticket {} to {}".format(ticket, viewer.twitch_name))
self.tickets[ticket] = viewer
def calculate_total_points(self):
"""
Gets the total amount of points awarded to all
viewers.
"""
self.total_points = 0
for viewer in self.viewers:
self.total_points += viewer.points2
self.total_points_percent = self.total_points / 100
print("Total points awarded (total tickets): %s" % self.total_points)
def draw(self):
"""
Picks a random number between 1 and total tickets, finds
the user that has been assigned tickets within that range and
returns the user.
"""
ticket = random.randint(1, self.total_points)
try:
winner = self.tickets[ticket]
except:
pdb.set_trace()
print("\n===== WINNER Twitch: {} / Beam: {} =====\n".format(winner.twitch_name, winner.beam_id))
print("Picked ticket {}\n".format(ticket))
print("Winner win chance: {:f}".format(winner.win_chance(self.total_points)))
print("Winner's ticket range: {}-{}".format(winner.tickets.start, winner.tickets.stop))
print("Winner's ticket amount: {}\n".format(winner.points2))
self.display_viewer(winner)
def display_random_viewer(self):
"""
Displays random viewer.
"""
self.display_viewer(self.get_random_viewer())
def display_viewer(self, viewer):
"""
Outputs the data on all viewers.
"""
print("""Viewer ID: %s\nTwitch Name: %s\nBeam Name: %s\nBeam ID: %s\nRank: %s\nPoints: %s\nPoints2: %s\nHours: %s\nRaids: %s\nGains Currency: %s\nGains Hours: %s\nInGiveaways: %s\nLastSeen: %s\nEntrance Message: %s\nEntranceMsgType: %s\nEntranceSFX: %s"""
% (
viewer.viewer_id,
viewer.twitch_name,
viewer.beam_name,
viewer.beam_id,
viewer.rank,
viewer.points,
viewer.points2,
viewer.hours,
viewer.raids,
viewer.gains_currency,
viewer.gains_hours,
viewer.in_giveaways,
viewer.last_seen,
viewer.entrance_message,
viewer.entrance_message_type,
viewer.entrance_sfx
)
)
def get_random_viewer(self):
"""
Gets a completely random viewer.
"""
return random.choice(self.viewers)
def get_viewers(self):
"""
Gets data on all the viewers in the database and stores
the data in self.viewers.
"""
c = self.db_conn.cursor()
viewers = c.execute('''
SELECT
viewer_id,
TwitchName,
BeamName,
BeamID,
Type,
Rank,
Points,
Points2,
Hours,
Raids,
GainsCurrency,
GainsHours,
InGiveaways,
LastSeen,
Sub,
EntranceMessage,
EntranceMsgType,
EntranceSFX
FROM Viewer
WHERE Type != 1
AND TwitchName NOT IN (
\'treeboydave\',
\'treebotdave\'
);
''').fetchall()
self.viewers = []
for cur_viewer in viewers:
self.viewers.append(
Viewer(
cur_viewer[0],
cur_viewer[1],
cur_viewer[2],
cur_viewer[3],
cur_viewer[4],
cur_viewer[5],
cur_viewer[6],
cur_viewer[7],
cur_viewer[8],
cur_viewer[9],
cur_viewer[10],
cur_viewer[11],
cur_viewer[12],
cur_viewer[13],
cur_viewer[14],
cur_viewer[15],
cur_viewer[16],
cur_viewer[17]
)
)
if __name__ == '__main__':
dd = DaveDraw()
dd.draw()
All your other SQL columns are capitalised, any chance that's why it's not finding the viewer_id column? Maybe it's Viewer_Id or similar?
If you sql execute 'HELP TABLE Viewer' and print what it returns, it will give you an outline of all of the columns in that database table, so you can make sure you have the capitalisation correct, or whether the column actually isn't there at all.

How to append to a list using another list of namedtuples?

so I'm very new to Python and got stuck on a problem for my introductory CS class. The problem is to create a a list containing all titles created before 2000 and all titles created after 2000. This is what I have so far:
from collections import namedtuple
Book = namedtuple("Book", "author title genre year price instock")
book_1 = Book("Bob", "Harry Potter", "Fantasy", 2000, 6.00, 1000)
book_2 = Book("Martha", "Hunger Games", "Psychological", 1998, 10.00, 2000)
book_3 = Book("Sam", "The Quest", "Adventure", 2010, 8.00, 5000)
book_4 = Book("Damien", "Pokemon", "Sci-Fi", 1990, 12.00, 10000)
book_5 = Book("Voldemort", "Maze Runner", "Adventure", 2015, 10.00, 50)
book_6 = Book("Anonymous", "Horror Stories Before Bed", "Horror", 2017, 18.00,0)
book_store_inventory = [book_1, book_2, book_3, book_4, book_5, book_6]
before_2000 = []
after_2000 = []
for i in book_store_inventory:
if book_store_inventory[i].year <= 2000:
before_2000.append(i.title)
else:
after_2000.append(i.title)
What should I change around from this point? I keep getting error messages saying list indices must be integers or slices, not Book. Thanks!
you don't need an index:
for book in book_store_inventory:
if book.year <= 2000:
before_2000.append(book.title)
else:
after_2000.append(book.title)
before_2000 = [i.title for i in book_store_inventory if i.year <= 2000]
after_2000 = [i.title for i in book_store_inventory if i.year > 2000]
Since you have so many book objects, it may make sense to create a new class to store the books and create property decorators to access the library data based on the certain condition:
class Library:
def __init__(self, books):
self.books = books
#property
def before_2000(self):
return [i for i in self.books if i.year <= 2000]
#property
def after_2000(self):
return [i for i in self.books if i.year > 2000]
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, ', '.join(i.title for i in self.books))
book_store_inventory = [book_1, book_2, book_3, book_4, book_5, book_6]
library = Library(book_store_inventory)
print(library.before_2000)
print(library.after_2000)
print(library)
Output:
[Book(author='Bob', title='Harry Potter', genre='Fantasy', year=2000, price=6.0, instock=1000), Book(author='Martha', title='Hunger Games', genre='Psychological', year=1998, price=10.0, instock=2000), Book(author='Damien', title='Pokemon', genre='Sci-Fi', year=1990, price=12.0, instock=10000)]
[Book(author='Sam', title='The Quest', genre='Adventure', year=2010, price=8.0, instock=5000), Book(author='Voldemort', title='Maze Runner', genre='Adventure', year=2015, price=10.0, instock=50), Book(author='Anonymous', title='Horror Stories Before Bed', genre='Horror', year=2017, price=18.0, instock=0)]
Library(Harry Potter, Hunger Games, The Quest, Pokemon, Maze Runner, Horror Stories Before Bed)

Categories

Resources