Generating a list to store input data - python

I am writing a program that keeps tab of the score of a card game and by the completion of the game generates a table with names of players, points and total profit/loss. I need some advice on how to execute one crucial aspect of scoring keeping for this project and hence I'll start by giving you the main lines of code of the project:
# takes player information//
player_number = int(input('number of players:'))
cards_per_player = int(input('cards per player:'))
# takes player data and generates dictionary
player_dict = {}
for x in range(1,player_number+1):
player_dict["player{0}".format(x)] = input('name of player:')
print (player_dict)
# takes the dictionary values and creates a list
players_keys = list(player_dict.values())
# function that takes an input for the 'hands' won for each round for each player in the game...maximum hands for each player are 3 and minimum are 0.
def round():
counter_for_round = []
for i in range(0,(len(players_keys))):
score_per_player = int((input(str(players_keys[i])+':')))
counter_for_round.append(score_per_player)`
The counter_for_round variable stores data on each player's count of hands for any particular round. For example, if the total number of players were three, the list would look like: [1,1,0] or [3,0,0] or [2,1,0] and etc etc. Now, what I want it is to generate variables with empty lists for each item within the list 'players_keys'. So, for example, if players_keys = [a,b,c], I want to generate three variables, a b and c, which are empty lists in order for me to store the total scores within them for each player.
How do I go about this? Also, I know that this method can be quite detrimental and hence I am curious as to whether you can think of a simpler way to execute this?

Since you dont know how many players there are, you shouldnt try to create "new variables" for each player, but use a dictionary instead like you already did with player_dict.
So your result would be score = {key: list() for key in players_keys}, which is a dictionary with every player name as a key and an empty list as a value.
Also i'm not sure why you even need player_dict since the new score variable would include all important information. So maybe merging input of player names and list creation would be better.
# takes player data and generates dictionary
player_dict = dict()
for x in range(0, player_number):
player_name = input('name of player:')
player_dict[player_name] = list()
# takes the dictionary values and creates a list
players_keys = list(player_dict.keys())

Related

How to make random number values for a dictionary that stay the same

Title isn't great, sorry.
I am new to python and I am playing around with dictionaries to further my understanding of them.
To practice, I am making a football team of 11 players. Each player is a dictionary stored in a list.
So each player will have its own dictionary but all the keys will be the same throughout, it's just the values that will change.
I have made the players positions and now I want to add the age of the player. This is what I have:
footballers = []
for populating in range(11): #populating = to get footballers
new_player = {"position": 'goalkeeper',}
footballers.append(new_player)
for baller in footballers[1:5]:
baller["position"] = 'defender'
print (baller)
for player in footballers[5:8]:
player["position"] = "midfield"
for player in footballers[8:11]:
player["position"] = "forward"
import random
for baller in footballers:
baller["age"] = random.randint (17, 34)
print (baller)
This works and I get the desired result. However, the age changes every time I run the code.
How would I make it so that I run it once and the value of the key stays the same?
I know I could just type the ages out myself but if I wanted to populate a whole league, I'm not doing that.
I've tried other ways such as making the age:value in another list of dictionaries but I couldn't figure out how to put the 2 together.
Is there something I'm missing here?
Thanks
A seed allows to 'randomly' populate a list with the same values every call.
It's important to have the seed outside the loop.
import random # good practice is to have imports at the top
footballers = []
for populating in range(11):
new_player = {"position": 'goalkeeper',}
footballers.append(new_player)
for baller in footballers[1:5]:
baller["position"] = 'defender'
print (baller)
for player in footballers[5:8]:
player["position"] = "midfield"
for player in footballers[8:11]:
player["position"] = "forward"
random.seed(42)
# the correct position is anywhere before the loop to have the same ages every call
for baller in footballers:
## random.seed(42) # Wrong position - will result in each player have the same age
baller["age"] = random.randint (17, 34)
print (baller)
Notes:
When you run your code in jupyter random.seed() needs to be in the same cell as the random call
42 is just an example, you can use any positive integer

Returning a value based on matching one lists values to another list based on order

I have four lists:
user = [0,0,1,1]
names = ["jake","ryan","paul","david"]
disliked_index = [0,1]
ranked_names = ["paul","ryan","david","jake"]
List "user" holds a user's response to which names they like (1 if like, 0 if dislike) from list "names". disliked_index holds the list spots that user indicated 0 in the user list. ranked_names holds the names ranked from most popular to least popular based on the data set (multiple students). What I am trying to achieve is to return the most popular name that the user responded they didn't like. So that
mostpopular_unlikedname = "ryan"
So far what I have done is:
placement = []
for i in disliked_index:
a = names[i]
placement.append(a)
Where I now have a list that holds the names the user did not like.
placement = ["jake","ryan"]
Here my logic is to run a loop to check which names in the placement list appear in the ranked_names list and get added to the top_name list in the order from most popular to least.
top_name =[]
for i in range(len(ranked_names)):
if ranked_names[i] == placement:
top_name.append[i]
Nothing ends up being added to the top_name list. I am stuck on this part and wanted to see if this is an alright direction to continue or if I should try something else.
Any guidance would be appreciated, thanks!
You don't really need disliked_index list for this. Just do something along these lines:
dis_pos = []
for name, sentiment in zip(names,user):
if sentiment == 0:
dis_pos.append(ranked_names.index(name))
mostpopular_unlikedname = ranked_names[min(dis_pos)]
print(mostpopular_unlikedname)
Output:
ryan

Create random, unique variable names for objects

I'm playing around with Python and any programming language for the first time, so please bear with me. I started an online class two weeks ago, but try to develop a small game at the side to learn faster (and have fun). It's a text adventure, but is shall have random encounters and fights with enemies that have random equipment that the players can then loot.
This is my problem: If I create random objects/weapons for my random encounter, I need to make sure that the object has a unique name. The way the level is designed there could in theory be an infinite number of objects (it can be open ended, with encounters just popping up).
This is my approach so far
class Item_NPCs: #create objects for NPCs
def__init__(self, item_type, item_number):
# e.g. item_type 1 = weapons, item_type2 = potions, etc.
if item_type == 1 and item number == 1:
self.property1 = 5
self.property2 = 4
if item_type == 1 and item_number ==2:
# etc. :)
def prepare_encounter():
inventory_NPC = [] # empty list for stuff the NPC carries around
XXX = Class_Item(item_type, item_number) # I might randomize the arguments.
What is important is that I want "XXX" to be unique and random, so that no object exists more than once and can later be put into the player's inventory.
How to do that?
Joe
Why do you need it to be random ? You could simply use a list, and append every new object to the list, with its index being its unique identifier :
items = []
items.append( Class_Item(item_type, item_number) )
But if you really need random identifier, maybe you can use a dictionary :
items = dict()
items[random_id] = Class_Item(item_type, item_number)
This requires random_id to be hashable (but it should be if it is a number or a string).
I don't know why others haven't thought of this:
yourvariableName = randint(0,1000)
exec("var_%s = 'value'" % yourVariableName)
I just thought of it myself. I hope it helps you.
A downside is you can't just do this:
print(var_yourVariableName)
you can only do this:
exec("print(var_%s)" % yourVariableName)
But you can probably circumvent this one way or another. Leave a comment if you manage to figure it out.
One more downside — if used in certain ways, it could be very insecure (as we are using exec), so make sure to cover any holes!

Separating lists in a list through iteration

First off, this is a homework assignment, but I've been working on it for a week now and haven't made much headway. My goal for this function is to take a list of lists (each list contains data about a football player) and separate the lists based off of the teams which the players belong to. I also want to add up each player's data so that I wind up with one list for each team with all the player's stats combined.
Here's the code I have so far. The problem I'm currently running into is that some teams are printed multiple times with different data each time. Otherwise it appears to be working correctly. Also, we have the limitation imposed on us that we are not allowed to use classes.
def TopRushingTeam2010(team_info_2010): #running into trouble calculating the rusher rating for each team, it also prints out the same team multiple times but with different stats. And just not getting the right numbers and order.
total_yards = 0
total_TD = 0
total_rush = 0
total_fum = 0
#works mostly, but is returning some teams twice, with different stats each time, which
#should not be happening. so... yeah maybe fix that?
for item in team_info_2010:
team = item[0]
total_yards = item[2]
total_TD = item[3]
total_rush = item[1]
total_fum = item[4]
new_team_info_2010.append([team, total_yards, total_TD, total_rush, total_fum])
for other_item in team_info_2010:
if other_item[0] == team:
new_team_info_2010.remove([team, total_yards, total_TD, total_rush, total_fum])
total_yards = total_yards + other_item[2]
total_TD = total_TD + other_item[3]
total_rush = total_rush + other_item[1]
total_fum = total_fum + other_item[4]
new_team_info_2010.append([team, total_yards, total_TD, total_rush, total_fum])
Any help or tips as to which direction I should head, or if I'm even headed in the right direction?
One possible problem is that you are removing from team_info_2010 while you are iterating through the list. Try deleting that line of code. I don't see a clear reason why you would want to delete from team_info_2010 and behavior is often undefined when you modify an object while iterating through it. More specifically, try deleting the following line of code:
team_info_2010.remove(item)

Using a Loop to Pair Indexes in Python

Please be patient. I'm new to Python and only 1 month in. In this proect, I import a file that simulates a list of names with associated scores. I'm having a hard time creating a loop that will print out the 1st index and its associated pair. My program needs to
divide the player list in half, and generate pairs using a player from each half of the list. For example, if there are 10 players sorted by rating, player 1 plays player 6, 2 plays 7, etc.
Can someone give me a quick guide into the correct direction? My sample code is below, which once completed, I will need to make this into a program with working functions.
def main():
myfile = open('CHESS.txt','r')
players = []
for line in myfile:
line = line.rstrip('\n')
players.append(line)
players.sort()
for i in players:
m=len(players)/2
print(players[0], players[0+m])
myfile.close()
main()
You're close. You just need to use an index i for each element in your list.
m=len(players)/2
for i in range(m):
print(players[i], players[i+m])
Note that this requires you have an even number of players.
Classic use case for zip:
>>> players = ["Player{}".format(i) for i in range(20)]
>>> half = len(players)/2
>>> pairs = zip(players[:half], players[half:])
>>> pairs
[('Player0', 'Player10'), ('Player1', 'Player11'), ('Player2', 'Player12'), ('Player3', 'Player13'), ('Player4', 'Player14'), ('Player5', 'Player15'), ('Player6', 'Player16'), ('Player7', 'Player17'), ('Player8', 'Player18'), ('Player9', 'Player19')]

Categories