Get sum of goals scored by each team - python

I am analyzing a football games dataset and I want to answer a question - how many goals each team has scored and lost.
My dataset:
date home_team away_team home_score away_score
1873-03-08 England Scotland 0 1
1873-03-09 Scotland England 1 0
... ... ... ... ...
The function takes in 2 parameters - start year and end year
I've tried to have an empty list at a start, while iterating through the whole set add the name of the country and append the goals they've scored but since there are many different teams my list is not correct.
def total_goals(start, end):
x = 0
goals_scored = 0
goals_scored_list = []
goals_lost = 0
goals_lost_list = []
complete_list = []
for item in range(len(data['home_team'])):
date = int(data['date'][x][:4])
if date >= start:
if date <= end:
if int(data['home_score'][x]) > int(data['away_score'][x]):
goals_scored_list.append(data['home_team'])
goals_scored_list.append(data['home_score'])
x += 1
else:
x += 1
return goals_scored_list
My desired output would be a list which would contain a list for each unique team, that list would have country name, goals scored and goals lost:
[['England',1,1],['Scotland',0,2],[...]]
I assume I would need to create a list for each unique country, maybe using something like
if country not in data['home_team']:
goals_scored_list.append(data['home_team'][x]
But I believe there is a more sophisticated way to achieve my goal.

I believe this should work:
class Team:
def __init__(self,name):
self.name = name
self.wins = 0
self.losses = 0
def addEl(self,pos,score):
try:
score = int(score)
except Exception as e:
print e
if pos:
self.wins += score
else:
self.loss += score
def total_goals(start,end):
d = {}
for i in range(len(data)):
date = int(data['date'][i])
if date >= start and date <= end: #make sure it's in the params
pos = int(data['home_score'][i]) > int(data['away_score'][i]) #true if home wins, false otherwise
if data['home_team'][i] in d: #check if home_team already exists
d[data['home_team']].addEl(pos,data['home_score'][i]) #add score to wins/losses
else:
d[data['home_team'][i]] = Team(data['home_score'][i])
d[data['home_team'][i]].addEl(pos,data['home_score'][i])
if data['away_team'][i] in d:
d[data['away_team']].addEl(not(pos),data['away_score'][i])
else:
d[data['away_team'][i]] = Team(data['away_score'][i])
d[data['away_team'][i]].addEl(not(pos),data['away_score'][i])
return d
Using a custom class has the advantage of letting you add more characteristics like how many games were won/lost, additional statistics etc.etc.

Related

how can I create class objects using a list?

This is my class program, for the instances I've created so far, it's worked fine.
from random import random
class team:
wins = 0
losses = 0
def __init__(self,name):
self.name = name
def win(self):
self.wins += 1
def lose(self):
self.losses += 1
def play(self,opponent):
if random()<0.5:
self.win()
opponent.lose()
print(self.name,"won",opponent.name,"lost")
else:
self.lose()
opponent.win()
print(opponent.name,"won",self.name,"lost")
def record(self):
return (self.wins,'-',self.losses)
def startgames(self, array_of_team_objects):
k = 1
outer = 0
space = True
while outer<len(array_of_team_objects):
inner = 0
while space == True:
inner = outer + k
if inner == len(Teams): space = False
array_of_team_objects[outer].play(array_of_team_objects[inner])
k +=1
#whileinner
outer+=1
#whileouter
print("Every team has now played every other team once")
team1 = team("Yankees") # creates a team object with given name
team2 = team("Mets") # each new team starts with 0 wins and 0 losses
team1.play(team2) #prints "Yankees won, Mets lost" or "Mets won, Yankees lost"
print(team1.record()) # should print "1-0" or "0-1" depending on above
print(team2.record()) # should print "0-1" or "1-0" depending on above
For the next part of this program, which I will use the 'startgames' method for, I want to make every element of the list 'Names' an object of the class. How can I do this?
Names =["Mets","Yankees","Dodgers","Cubs","Nationals","Rays","Marlins","Braves","Twins","Athletics","Orioles","Royals","Phillies","Pirates"]

How to add a currency symbol to my array?

Goal:
Display my list of commission pay with a £ symbol.
Explanation of what the problem is:
When it comes to displaying the result it does not print the whole result instead it just prints the £ symbol.
What I have tried:
As you can see in the code, I have attempted to convert the array into a string (putting it into its own variable) then I added the currency symbol (£) to it and asked for commission2 to be called. However, it does not show.
OUTPUTTED:
Name Id Houses Sold Commission
£1000
ki 2 2 £
(the £1000 is just to show that the data is actually there, but for some reason when printing in the list, it is not displayed...)
OUTPUT DESIRED:
Name Id Houses Sold Commission
ki 2 2 £1000
I've been at it for hours so any help would be greatly appreciated!
Code where the error occurs:
def print_entered_info(names, ids, num_sold_houses):
print()
row_width = 12
comission_per_house = 500
header = ['Name', 'Id', 'Houses Sold', 'Commission']
print(' '.join(f'{h:<{row_width}}' for h in header))
commission = [n * comission_per_house for n in num_sold_houses]
commission2 = commission
commission2 = ''.join(str(e) for e in commission)
commission2= "£" + commission2
print(commission2)
for values in zip(*[names, ids, num_sold_houses, commission2]):
print()
print(' '.join(f'{v:<{row_width}}' for v in values))
My full code:
def get_int_input(prompt: str) -> int:
num = -1
while True:
try:
num = int(input(prompt))
break
except ValueError:
print('Error: Enter an integer, try again...')
return num
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
names = []
ids = []
num_sold_houses= []
def get_single_employee_info(names, ids, num_sold_houses):
names.append(input('What is the employee\'s name?: '))
ids.append(get_int_input('What is the employee\'s id?: '))
num_sold_houses.append(get_int_input('How many houses did the employee sell?: '))
def get_houses_sold_info(names, ids, num_sold_houses):
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input('Add another employee [yes/no]?: ')
while add_another_employee:
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input(
'Add another employee [yes/no]?: ')
def print_entered_info(names, ids, num_sold_houses):
print()
row_width = 12
comission_per_house = 500
header = ['Name', 'Id', 'Houses Sold', 'Commission']
print(' '.join(f'{h:<{row_width}}' for h in header))
commission = [n * comission_per_house for n in num_sold_houses]
commission2 = commission
commission2 = ''.join(str(e) for e in commission)
commission2= "£" + commission2
print(commission2)
for values in zip(*[names, ids, num_sold_houses, commission2]):
print()
print(' '.join(f'{v:<{row_width}}' for v in values))
print()
total_commission = sum(commission)
print(f'Total Commission: £{total_commission}.00 (before bonus)')
print()
bonus = max(commission)
if bonus >= max(commission):
bonus = bonus*0.15
bonus = (int(max(commission)) + bonus)
commission = bonus
print("The person at the top of ranking gets: " + "£" + str(commission)+"0")
print()
rankings = sorted(zip(num_sold_houses, names), reverse=True)
print('Ranking:')
for houses_sold, name in rankings:
print(f'{name} - {houses_sold}')
def main() -> None:
print('Houses Sold Tracker')
print('===================')
names, ids, num_houses_sold = [], [], []
get_houses_sold_info(names, ids, num_houses_sold)
print_entered_info(names, ids, num_houses_sold)
if __name__ == '__main__':
main()
Change out
commission2 = ''.join(str(e) for e in commission)
to
commission2 = ["£" + str(e) for e in commission]
and remove the line under it. Your ''.join was taking 2 list elements and forcing them into a single string, which is not what you want for this logic. You want a list output for the commission2 variable so we create a list and append the stringified values to it along with the currency symbol.
Output:
Name Id Houses Sold Commission
Kevin 1 3 £1500
Stacey 2 5 £2500
Total Commission: £4000.00 (before bonus)
The person at the top of ranking gets: £2875.00
Ranking:
Stacey - 5
Kevin - 3

Can I pass sqlite3 table column name as search parameter?

My first help request on Stack Overflow. Python version 3.6.4
I have an issue with my code. It is meant to to return a price quote based on parameters entered - such as country, shipment weight and in what zone is the city in given country.
The table looks like something this(excel picture).
Screenshot Image
Is it possible to narrow down which column to use. Such as if search parameters are estonia and 3 kgs it nicely returns all three columns of zone1, zone2 and zone3:
What country? :estonia
weight?: 70
('estonia', '75', '10,83', '12,25', '14,43')
But can I pass in an argument based on user input to narrow down which zone column to use to get the value?
For example if a city is in zone1, take only values from column zone1 based on other search parameters
My robust code is as follows:
import sqlite3
import pandas as pd
conn = sqlite3.connect("transportHinnakiri.db")
c = conn.cursor()
df = pd.read_csv("baltikum.csv")
df.to_sql("baltikum", conn, if_exists="append", index=False)
input_country = input("What country? :").lower()
input_weight = int(input("Weight?: "))
def weight_category(input_weight):
if input_weight < 1:
return 1
elif 1 < input_weight <= 3:
return 3
elif 3 < input_weight <= 10:
return 10
elif 10 < input_weight <= 20:
return 20
elif 20 < input_weight <= 31.5:
return 31.5
elif 31.5 < input_weight <= 50:
return 50
elif 50 < input_weight <= 75:
return 75
elif 75 < input_weight <= 100:
return 100
result = weight_category(input_weight)
def get_post():
c.execute("SELECT * FROM baltikum WHERE country=? AND weight=?",(input_country, result))
row = c.fetchone()
return row
result_final = get_post()
print(result_final)`
I'm not sure if this is what you are looking for but here is how I would do it. First get the city from the user:
city = input("input City: ").lower()
Then I would create some data structure, say dictionary, that holds all the zones and their cities:
zones = {'zone1': ['boston', 'new york'], 'zone2': ['san fransisco', 'los
angeles']}
Then you can have a function that takes in a city and returns a zone
def get_zone(city):
for zone in zones.keys():
if city in zones[zone]:
return zone
return "Error city not found"
Of course you would have to do something to normalize user input. Then you could create a command string and execute the command
def execute_command(zone, weight, country):
cmd = "SELECT {zone} FROM baltikum WHERE country={country} AND weight={weight}".format(zone = zone, country = country, weight = weight)
data = c.execute(cmd)
return data
Then you only get data from selected zone. Hope this helps!

Returning count of more persons

I am new in python and I have problem in my code. My function count_transitive_sellers_with_degree is returning count only from person sellers. I need to get it return count of person sellers and seller sellers and so on. I do not know how to write it.. Could you help me and say where it is a problem? Thank you :)
class Person:
def __init__(self, name, year_of_birth, degree):
self.name = name
self.year_of_birth = year_of_birth
self.degree = degree
self.leader = None
self.sellers = []
def create_leadership(leader, seller):
seller.leader = leader
leader.sellers.append(seller)
def count_transitive_sellers_with_degree(person, degree):
count = 0
for seller in person.sellers:
if seller.degree == degree:
count += 1 + count_transitive_sellers_with_degree(seller,degree)
return count
>>> martin = Person('Martin', 1991, 'phd')
>>> tom = Person('Tom', 1993, 'mgr')
>>> josh = Person('Josh', 1995, 'bc')
>>> create_leadership(martin, tom)
>>> create_leadership(tom, josh)
>>> count_transitive_sellers_with_degree(martin, 'bc')
what it should write... -> 1
what it is writing now... -> 0
Currently you're only calling count_transitive_sellers_with_degree on sellers who themselves have the degree you're testing for, I haven't tested the below, but I think it should work.
def count_transitive_sellers_with_degree(person, degree):
count = 0
for seller in person.sellers:
if seller.degree == degree:
count += 1
# A seller's sellers should be counted irrespective of
# if they have the degree or not
count += count_transitive_sellers_with_degree(seller,degree)
return count
Your problem is here. Your if condition is not allowing you to go the recursive part as Tom's degree is not 'bc'.
if seller.degree == degree:
count += 1 + count_transitive_sellers_with_degree(seller,degree)
if seller.degree == degree:
does not reflect what you say your program is supposed to do: it will only add the children of the person if they have the same degree

Can't figure out a Python exercise with dictionaries

I have the following code:
shoppingList = ["banana","orange","apple"]
inventory = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def calculateBill(food):
total = 0
for k in food:
total += prices[k]
return total
calculateBill(shoppingList)
The exercise tells me to complete the function following these instructions:
Don't add the price of an article in your bill if it is not in your inventory.
After you buy an article, substract one from the inventory.
I don't know how to do it and I don't know if I have any other mistakes in my code.
If it isn't clear, the value in inventory is the stock of that item, and the value in "prices" is the price.
First of all, I don't see comida defined anywhere before its use. I'll assume that by comida, you mean food.
Here is a simple solution:
def calculateBill(food):
total = 0
for k in food:
if inventory.get(k, 0) > 0:
total += prices[k] # updates total
inventory[k] = inventory[k] - 1 # updates inventory
return total
You could do the following
def calculateBill(food):
total = 0
for k in food:
if k in inventory:
if inventory[k] > 0:
total += prices[k]
inventory[k] = inventory[k] - 1
else:
print 'There are no %s in stock' % k
else:
print 'dont stock %s' % k
return total
For 1)
if k in inventory:
Will check if the key is present in your inventory dict.
For 2)
inventory[k] = inventory[k] - 1
Will substract 1 from your inventory
One flaw in this code is that it does not check that the inventory count is above 0 before allowing to buy. So
if inventory[k] > 0:
Does this.
Here's a complete solution.
class Error(Exception):
"""Base class for Exceptions in this module"""
pass
class QtyError(Error):
"""Errors related to the quantity of food products ordered"""
pass
def calculateBill(food):
def buy_item(food_item, qty=1, inv_dict=None, prices_dict=None):
get_price = lambda item,price_dct: price_dct.get(item,9999999)
if inv_dict is None:
inv_dict = inventory
if prices_dict is None:
prices_dict = prices
if inv_dict.get(food_item, 0) >= qty:
inv_dict[food_item] -= qty
return sum(get_price(food_item, prices_dict) for _ in range(qty))
else:
raise QtyError("Cannot purchase item '{0}' of quantity {1}, inventory only contains {2} of '{0}'".format(food_item, qty, inv_dict.get(food_item,0)))
total = sum(buy_item(food_item, 1, inventory, prices) for food_item in food)
return total

Categories

Resources