How to create combinations with constrains in Python - python

I have a list of football players. Each player has three attributes: position (G, D, M, A), name and salary.
Position Name Salary
P Buffon 6
D Maldini 23
D Baresi 15
D Bergomi 7
C Kakà 33
C Gomez 18
A Ronaldo 52
A Vieri 44
...
I want to create all possible combinations of a football team which contains exactly 11 players. These are the constrains:
Players constrain: total elements = 11
Position constrain: P = 1, D = 4, C = 4, A = 2
Salary constrain: sum salary < 200
I have started researching and it looks to me that itertools could help me generate all possible teams given the constrains. But what is not clear to me is how to code the constrains.
subset = df[['position', 'name', 'salary']]
tuples = [tuple(x) for x in subset.values]
all_permutations = itertools.permutations(tuples)
for perm in all_permutations:
# constrains

The itertools library has a very nice function for iterating through combinations. You can get all combinations of 11 players, and then filter through those.
from collections import Counter
import itertools
def valid_team(team):
positions = []
salary = 0
for player in team:
(player_pos,_,player_salary)=player
positions.append(player_pos)
salary += player_salary
pos_count = Counter(positions)
return (
pos_count['P'] is 1 and
pos_count['D'] is 4 and
pos_count['C'] is 4 and
pos_count['A'] is 2 and
salary<200
)
for team in itertools.combinations(players,11):
if (valid_team(team)):
print("found valid team")
print(team)
else:
print("found invalid team")
It should be noted that there is lot of unnecessary processing in the above method, as you can select each position individually. Alternative implementation below.
players_sorted = {}
for player in players:
if player[0] not in players_sorted:
players_sorted[player[0]] = []
players_sorted[player[0]].append(player)
p_guys = itertools.combinations(players_sorted['P'],1)
d_guys = itertools.combinations(players_sorted['D'],4)
c_guys = itertools.combinations(players_sorted['C'],4)
a_guys = itertools.combinations(players_sorted['A'],2)
teams = itertools.product(p_guys,d_guys,c_guys,a_guys)
for team in teams:
team_players = []
for pos in team:
team_players.extend(pos)
if (valid_team(team_players)):
print("found valid team")
print(team)
else:
print("found invalid team")
print(team)

You can use simple recursion with a generator:
from collections import Counter
pos_c = {'P':1, 'D':4, 'C':4, 'A':2}
def teams(d, c = []):
if len(c) == 11:
yield c
else:
s, pos = sum(int(j) for *_, j in c), Counter([j for j, *_ in c])
for i in d:
if not c or (i not in c and s+int(i[-1]) < 200 and pos_c[i[0]] >= pos.get(i[0], 0)+1):
yield from teams(d, c+[i])

Related

Dictionary task in Python: Elections

The first line gives the number of entries. Further, each entry contains the name of the candidate and the number of votes cast for him in one of the states. Summarize the results of the elections: for each candidate, determine the number of votes cast for him. Use dictionaries to complete the tasks.
Input:
Number of voting records (integer number), then pairs <> - <>
Output:
Print the solution of the problem.
Example:
Input:
5
McCain 10
McCain 5
Obama 9
Obama 8
McCain 1
Output:
McCain 16
Obama 17
My problem is at the step when I have to sum keys with same names but different values.
My code is:
cand_n = int(input())
count = 0
countd = 0
cand_list = []
cand_f = []
num = []
surname = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
cand_list.append(cand_f)
for k in cand_list:
for i in k:
if i.isdigit():
num.append(int(i))
else: surname.append(i)
while countd < cand_n:
edict[surname[countd]] = num[countd]
countd += 1
print(edict)
You can add the name and vote to the dictionary directly instead of using one more for() and while().
If the name does not exist in the dictionary, you add the name and vote. If the name exists in the dictionary, increase the vote.
cand_n = int(input())
count = 0
cand_list = []
cand_f = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
if cand_f[0] in edict:
edict[cand_f[0]] += int(cand_f[1])
else:
edict[cand_f[0]] = int(cand_f[1])
print(edict)

probability of getting three of a kind by drawing 5 cards

so my goal is to try to simulate an actaul deck and draw five cards and check if there is a three of a kind. I have no problem making the deck and drawing five cards, the problem arises when i check for three of a kind
my code:
from random import shuffle, sample
from itertools import product
#generating deck
suits = ["s","d","h","c"]
values = ["1","2","3","4","5","6","7","8","9","10","11","12","13"]
deck = list(product(values,suits))
sim = 100000
three_of_a_kind = 0
for i in range(sim):
shuffle(deck)
#generating hand
hand = sample(deck,5)
#checking for three of a kind
if any(hand[0][0] == x[0] for x in hand):
three1 += 1
elif any(hand[1][0] == x[0] for x in hand):
three2 += 1
elif any(hand[2][0] == x[0] for x in hand):
three3 += 1
if three1 == 3 or three2 == 3 or three3 == 3:
three_of_a_kind += 1
prob_three = three_of_a_kind/sim
print(prob_three)
edit: my deck only had 12 cards and I changed it to 13 but my question has not changed
Using collections.Counter to count cards
# Counter(...) returns a dictionary of counts of card values
# Checking for count of 3 (card[0] is the card value in hand)
if any(v==3 for k,v in Counter(card[0] for cardin hand).items()):
three_of_a_kind += 1
Complete Code
from random import shuffle, sample
from itertools import product
from collections import Counter
#generating deck
suits = ["s","d","h","c"]
values = ["1","2","3","4","5","6","7","8","9","10","11","12","13"]
deck = list(product(values,suits))
sim = 100000
three_of_a_kind = 0
for i in range(sim):
shuffle(deck)
#generating hand
hand = sample(deck,5)
# Check for 3 of a kind by checking for 3 cards of same value
if any(v==3 for k,v in Counter(card[0] for card in hand).items()):
three_of_a_kind += 1
prob_three = three_of_a_kind/sim
print(f'{prob_three:.4%}')
Here is a little trick:
#checking for three of a kind
values = sorted(card[0] for card in hand)
if values.count(values[2]) == 3:
three_of_a_kind += 1 # three, but not four
If there are 3 equal values in a sorted list of length 5, it must look like one of these possibilities:
C C C x y
x C C C y
x y C C C
In each case the middle card value C = values[2] is the value we need to count.
For more general solutions see: collections.Counter
#checking for three of a kind
if 3 in collections.Counter(card[0] for card in hand).values():
three_of_a_kind += 1

Probability calculation in python

My problem is: I have 12 players, with 3 of them being named A, B and C, respectively. 12 players are being divided into 2 groups, 6 people each. I need to calculate the probability of player A and B being in the same team, and player C being in thе eopposite one. Math is not my strongsuit, because im pretty sure this is not a hard thing to calculate, but i would be really grateful if you could help me with this one. Here is what i wrote so far:
import random
playersnumb = 12
players = list(range(12))
A = random.choice([x for x in range(12)])
B = random.choice([x for x in range(12) if x != A])
C = random.choice([x for x in range(12) if (x != A) and (x != B)])
random.shuffle(players)
team1 = (players[:6])
team2 = (players[6:])
if A in team1:
print("Player A is in team 1")
else:
print("Player A is in team 2")
if B in team1:
print("Player B is in team 1")
else:
print("Player B is in team 2")
if C in team1:
print("Player C is in team 1")
else:
print("Player C is in team 2")
Any help is appreciated.
I wrote a little bit based on your code. The idea is to loop multiple times over your test code, it is not 100% accurate, but i think good enough for you:
import random
def calculate(playercount: int = 12) -> bool:
players = list(range(playercount))
player_a = random.choice([x for x in range(playercount)])
player_b = random.choice([x for x in range(playercount) if x != player_a])
player_c = random.choice([x for x in range(playercount) if (x != player_a) and (x != player_b)])
random.shuffle(players)
team1 = (players[:playercount//2])
team2 = (players[playercount//2:])
# That are your "positive" events
return (player_a in team1 and player_b in team1 and player_c in team2) or\
(player_a in team2 and player_b in team2 and player_c in team1)
def calculate_all(runtimes: int = 100000) -> float:
counter = 0
# count all poyitive events
for i in range(runtimes):
if calculate():
counter += 1
# return how often they appeared, based on all tests
return counter / runtimes
print("The probability is about {} %".format(calculate_all() * 100))
The number of ways to fill 1 list of six total = 12!/(6! * 6!) comb(12,6)
The number of ways to fill a list of six (including A and B and not C) = 9!/(4! * 5!) comb(9, 4)
Also, want to find (not A and not B and C) = 9!/(5! * 4!) comb(9, 5)
>>> from math import comb
>>> comb(12, 6)
924
>>> comb(9, 4) + comb(9, 5)
252
>>> 252 / 924
0.2727272727272727

Sorting 3 piles of numbers row by row left to right

Hey I need to sort out 3 lists in a special way after they have been mixed up and placed like in a deck row by row (Link to the full question):
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
Now the order is b, a, c and you have to place all of the numbers from left to right (I need to do this for a deck so the numbers will contain letters next to them making them a string).
Expected outcome:
a = [4,1,7]
b = [5,2,8]
c = [6,3,9]
*Note the lists that I am working on contain more than 3 values in them
Just zip them:
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=[7,8,9]
>>> a, b, c = map(list, zip(b, a, c)) # in the order specified: b, a, c
>>> a
[4, 1, 7]
>>> b
[5, 2, 8]
>>> c
[6, 3, 9]
It would also work with (but that changes the lists in-place):
>>> a[:], b[:], c[:] = zip(b, a, c)
Instead of the map(list, ...).
In case you have more values and want to distribute them:
>>> a=[1,2,3,4]
>>> b=[5,6,7,8]
>>> c=[9,10,11,12]
>>> tmp = b + a + c # concatenate them in the order
>>> # distribute them: every third element, starting with 0 (a), 1 (b) and 2 (c)
>>> a, b, c = tmp[::3], tmp[1::3], tmp[2::3]
>>> a
[5, 8, 3, 10]
>>> b
[6, 1, 4, 11]
>>> c
[7, 2, 9, 12]
Once the selected pile has been picked, you need to put the selected pile in the middle of the other two piles. One option would be just to combine the three different pile lists into one list, with the chosen pile in the middle.
if pile == 1: NewCards = Pile2 + Pile1 + Pile3
elif pile == 2: NewCards = Pile1 + Pile2 + Pile3
else: NewCards = Pile1 + Pile3 + Pile2
EDIT:
Okay, so you need to deal out the combination of the cards into 3 piles. You can loop through each of the decks, and deal them out. Make sure the right deck is in the middle! (In this case I'll use deck 2).
# create three empty temporary lists
temp = [[],[],[]]
cardnum = 0
# loop through the 3 decks
for i in range(3):
if i == 0: deck = partA
elif i == 1: deck = partB
else: deck = partC
# loop through the cards in the decks
for card in deck:
i = cardnum % 3 # mod 3 to split the cards among the decks
temp[i] += card
cardnum += 1
# update the decks now
partA = temp[0]
partB = temp[1]
partC = temp[2]
Hmmm .... an interesting problem :P
I am going to do some thing which i hate when people do to me... post code...
See if there is something here that helps you.
HINT HINT: Have a look at the get_order function.
from itertools import product, izip_longest
import random
def grouped(iterable, n, fillvalue=None):
return izip_longest(fillvalue=fillvalue, *[iter(iterable)] * n)
def get_order(selected, seq=[0,1,2]):
seq = [i for i in seq if i!=selected]
seq.insert(len(seq)/2, selected)
return seq
deck = ['-'.join(card) for card in product('c h d s'.split(), 'a 1 2 3 4 5 6 7 8 9 10 j q k'.split())]
plycards= random.sample(deck,21)
piles = [[],[],[]]
for idx, i in enumerate(grouped(plycards, 3)):
for idx, item in enumerate(i):
piles[idx].append(item)
print (i)
for j in range(0,3):
# Combine again
plycards = []
for i in get_order(int(raw_input('Which pile? '))-1):
plycards += piles[i]
print ('-------------')
piles = [[],[],[]]
for idx, i in enumerate(grouped(plycards, 3)):
for jdx, item in enumerate(i):
piles[jdx].append(item)
print (i)
print ("You selected card :'{}'".format(plycards[10])

Producing a sorted football league table in Python

I have created a program which simulates an entire football season between teams. The user inputs the teams' names and their skill ratings. It then uses the Poisson distribution to compare their skill ratings and calculate the result between the two teams. After each match, the relevant lists are updated: the winning teams gains 3 points (so if it is the third team that has won then the value at index [2] increases by 3). I have a separate list for points, goals scored, goals conceded, games won, games drawn, and games lost (side note - is there a more efficient way of doing this?)
The problem I have comes at the end of the season: each team is outputted with their data in the order that the teams were originally input. This is done using the fact that a team's name in the 'names' list is the same index as their points in the 'points' list. So the issue is, if I order the 'points' list then they will be out of sync with their names. I hope this makes sense but here is an example output for a season:
Enter number of teams in league: 4
Enter team 1 name: a
Enter team 2 name: b
Enter team 3 name: c
Enter team 4 name: d
Enter a skill: 1
Enter b skill: 3
Enter c skill: 5
Enter d skill: 8
===========================================
a's home games:
===========================================
a 2 - 0 b
a 0 - 2 c
a 0 - 0 d
===========================================
b's home games:
===========================================
b 2 - 3 a
b 1 - 0 c
b 0 - 0 d
===========================================
c's home games:
===========================================
c 1 - 0 a
c 1 - 0 b
c 0 - 1 d
===========================================
d's home games:
===========================================
d 4 - 0 a
d 2 - 0 b
d 0 - 0 c
Final table:
a Skill: 1 Points: 7 For: 5 Against: 9 Goal difference: -4 Wins: 2 Draws: 1 Losses: 3
b Skill: 3 Points: 4 For: 3 Against: 8 Goal difference: -5 Wins: 1 Draws: 1 Losses: 4
c Skill: 5 Points: 10 For: 4 Against: 2 Goal difference: 2 Wins: 3 Draws: 1 Losses: 2
d Skill: 8 Points: 12 For: 7 Against: 0 Goal difference: 7 Wins: 3 Draws: 3 Losses: 0
[4, 7, 10, 12]
So what I would now like to do is to be able to print a final league table in descending points order, rather than the way it prints now just in index order.
Sorry if this is poorly worded - the code for my program might be more useful so here it is:
import math
import random
#Lambda value in Poisson distribution for higher rated team
lambOne = 1.148698355
#Lambda value for lower rated team
lambTwo = 0.8705505633
#Poisson distribution calculating goals scored by the home team
def homeMatch(homeRating,awayRating):
global lambOne
global x
global y
if x == y:
raise ValueError
else:
lamb = lambOne**(int(homeRating)-int(awayRating))
homeScore = 0
z = random.random()
while z > 0:
z = z - ((lamb**homeScore * math.exp(lamb * -1))/(math.factorial(homeScore)))
homeScore += 1
return (homeScore-1)
#Poisson distribution calculating goals scored by away team
def awayMatch(homeRating,awayRating):
global lambTwo
global x
global y
#This check is to stop a team playing itself
if x == y:
raise ValueError
else:
lamb = lambTwo**(int(homeRating)-int(awayRating))
awayScore = 0
z = random.random()
while z > 0:
z = z - ((lamb**awayScore * math.exp(lamb * -1))/(math.factorial(awayScore)))
awayScore += 1
return (awayScore-1)
#Selecting number of teams in league
leagueSize = int(input("Enter number of teams in league: "))
#Initialising empty lists
teamNames = []
teamSkill = []
teamPoints = []
teamFor = []
teamAgainst = []
teamWins = []
teamDraws = []
teamLosses = []
#Populating lists with number of zeroes equal to the number of teams (one zero for each)
for x in range(leagueSize):
teamPoints += [0]
teamFor += [0]
teamAgainst += [0]
teamWins += [0]
teamDraws += [0]
teamLosses += [0]
#Entering names and skill ratings for each team
for i in range(leagueSize):
teamNames += [input("Enter team "+str(i+1)+" name: ")]
for j in range(leagueSize):
teamSkill += [input("Enter "+teamNames[j]+" skill: ")]
#Initialising variables
homeScore = 0
awayScore = 0
#The season begins - each team plays all of its home games in one go
for x in range(leagueSize):
#input("Press enter to continue ")
print("===========================================")
print(teamNames[x]+"'s home games: ")
print("===========================================\n")
for y in range(leagueSize):
error = 0
try:
homeScore = homeMatch(teamSkill[x],teamSkill[y])
#Skipping a game to stop a team playing itself
except ValueError:
pass
error += 1
try:
awayScore = awayMatch(teamSkill[x],teamSkill[y])
except ValueError:
pass
if error == 0:
#Updating lists
print(teamNames[x],homeScore,"-",awayScore,teamNames[y],"\n")
teamFor[x] += homeScore
teamFor[y] += awayScore
teamAgainst[x] += awayScore
teamAgainst[y] += homeScore
if homeScore > awayScore:
teamWins[x] += 1
teamLosses[y] += 1
teamPoints[x] += 3
elif homeScore == awayScore:
teamDraws[x] += 1
teamDraws[y] += 1
teamPoints[x] += 1
teamPoints[y] += 1
else:
teamWins[y] += 1
teamLosses[x] += 1
teamPoints[y] += 3
else:
pass
#Printing table (unsorted)
print("Final table: ")
for x in range(leagueSize):
#Lots of formatting
print(teamNames[x]+(15-len(teamNames[x]))*" "+" Skill: "+str(teamSkill[x])+(5-len(str(teamSkill[x])))*" "+" Points: "+str(teamPoints[x])+(5-len(str(teamPoints[x])))*" "+" For: "+str(teamFor[x])+(5-len(str(teamFor[x])))*" "+" Against: "+str(teamAgainst[x])+(5-len(str(teamPoints[x])))*" "+" Goal difference: "+str(teamFor[x]-teamAgainst[x])+(5-len(str(teamFor[x]-teamAgainst[x])))*" "+" Wins: "+str(teamWins[x])+(5-len(str(teamWins[x])))*" "+" Draws: "+str(teamDraws[x])+(5-len(str(teamDraws[x])))*" "+" Losses: "+str(teamLosses[x])+(5-len(str(teamLosses[x])))*" ")
teamPoints.sort()
print(teamPoints)
Sorry that this is very long and likely poorly worded and inefficient but I hope someone will be able to help me! Thank you very much :)
While your current approach is (barely) workable, it makes it very difficult to (for example) change the information you want to store about each team. You might consider defining a Team class instead, each instance of which stores all the information about a specific team.
class Team:
def __init__(self, name, skill):
self.name = name
self.skill = skill
self.points = self.goals_for = self.goals_against = \
self.wins = self.draws = self.losses = 0
This lets you create a new team object by passing a name and a skill level, in this way:
t1 = Team("Bradford City", 3)
t1 now has attributes name and skill with the given values, as well as a number of others (points, goals_for, and so on) whose values are all zero.
Then you can initialise the league quite easily:
league_size = 4
teams = []
for _ in range(league_size):
teams.append(Team(input("Name of team "+str(_)+": "),
int(input("Team "+str(_)+"'s skill level: ")))
Then to print the skill level of each team you can loop over the list:
for team in teams:
print(team.name, team.skill)
I hope this gives you some idea how your approach can be simplified. Your functions to play the matches can also take teams as arguments now, and modify the team objects directly according to the computed outcomes.
To get to the answer you want, once you have a list of teams you can print them out sorted by the number of points they hold quite easily:
for team in sorted(teams, key=lambda t: t.points):
print(team.name, team.skill, team.points, ...)
As far as I can see, none of your global declarations were necessary (if a name isn't defined locally Python will look for a global name to satisfy a reference). Besides which, inputs to a function should usually be passed as arguments, it's rather bad practice just to grab things from the environment!
I hope this is sufficient for you to rework your program to be more tractable. As a beginner I'd say you have done extremely well to get this far. The next steps are going to be exciting for you!
Added later: Your all-play-all could be easier to program as a result:
for home in teams:
for away in teams:
if home is away: # Teams don't play themselves
continue
play_match(home, away)
The play_match function would simulate the match and adjust each team's statistics. Of course you could simulate the away matches with another line reading
play_match(away, home)
though I'm not sure your algorithm is symmetrical for that.

Categories

Resources