Increasing values of entries across several dictionaries using user input - python

I am trying to make a part of a program that takes a users input, searches across several dictionaries to find a matching key, and then increase the corresponding entries value by 25.
Strength = {"Acrobatics":5, "Crafting":5, "Axe":5, "Blunt Weapon":5, "Long Blade":5}
Intelligence = {"Alchemy":5, "Conjuration":5, "Enchant":5, "Thievery":5}
Willpower = {"Alteration":5, "Destruction":5, "Mysticism":5, "Restoration":5}
Agility = {"Block":5, "Light Armor":5, "Marksman":5, "Sneak":5}
Speed = {"Athletics":5, "Hand to Hand":5, "Short Blade":5, "Unarmored":5}
Endurance = {"Heavy Armor":5, "Medium Armor":5, "Spear":5}
Personality = {"Illusion":5, "Mercantile":5, "Speechcraft":5}
# Skill dictionaries, will be printed to a seperate file after all things are done
skilldict = {"Strength":Strength, "Intelligence":Intelligence, "Willpower":Willpower, "Agility":Agility, "Speed":Speed, "Endurance":Endurance, "Personality":Personality}
for alphakey, alphaentry in skilldict.items():
if alphakey == usfavstat[0]:
for key, entry in alphaentry.items():
alphaentry[key] = entry + 5
for alphakey, alphaentry in skilldict.items():
# Grabs a key, entry combination from skilldict, named differently to not cause error down the line
if alphakey == usfavstat[1]:
# If the key is equal to the second favored stat, continue
for key, entry in alphaentry.items():
# This works?
# Nested for-loop grabbing a key, entry combination from a nested dict
alphaentry[key] = entry + 5
# Increases all values of entries by 5
mtemp = input("Enter major skills, seperated by a comma : ").title()
mtemp2 = mtemp.replace(" ", "")
majorskills = mtemp2.split(",")
# Stuff to increase corresponding skills by 25
I am unsure how to go about this. An example input would be "Acrobatics, Short Blade, Block, Speechcraft, Alteration". The desired output would have these skills at 30 in their respective dictionaries.
The for-loops with nested for-loops are irrelevant for this situation. I've included them to see if anyone would have a better means of achieving their goal, that being increasing all skills of an area by 5, based on user input in usfavstat, but this is secondary.
If there is information that would be beneficial to have, do comment and I'll add it if I can.

Here you go:
Strength = {"Acrobatics":5, "Crafting":5, "Axe":5, "Blunt Weapon":5, "Long Blade":5}
Intelligence = {"Alchemy":5, "Conjuration":5, "Enchant":5, "Thievery":5}
Willpower = {"Alteration":5, "Destruction":5, "Mysticism":5, "Restoration":5}
Agility = {"Block":5, "Light Armor":5, "Marksman":5, "Sneak":5}
Speed = {"Athletics":5, "Hand to Hand":5, "Short Blade":5, "Unarmored":5}
Endurance = {"Heavy Armor":5, "Medium Armor":5, "Spear":5}
Personality = {"Illusion":5, "Mercantile":5, "Speechcraft":5}
skill_dict = {"Strength":Strength, "Intelligence":Intelligence, "Willpower":Willpower, "Agility":Agility, "Speed":Speed, "Endurance":Endurance, "Personality":Personality}
user_input = input("Enter major skills, seperated by a comma: ").title()
major_skills = [skill.strip() for skill in user_input.split(",")]
for skill in skill_dict:
for major_skill in major_skills:
if skill_dict.get(skill).get(major_skill):
skill_dict[skill][major_skill] += 25
print(skill_dict)
I've re-named the variables a bit for my own convenience, but hope you get the idea.
By the way, I think mtemp2 = mtemp.replace(" ", "") is not a good idea in case you have some space-separated skills like Short Blade (since it becomes ShortBlade and fails), so I've replaced it with .strip() string method instead.

Related

How can I create a program that count votes that are being put by the user

I need to make 3 political parties like in an election. The program should ask "for which will you vote?" (showing the 3 political options), after 10 the user randomly inserts 10 votes, the program should count the votes and print the results.
I'm new to programming, I really don't know what I'm doing
print("today is election day! for who will u vote?")
polls=print("PLD","PRM","PRD")
1) In your question, you stated "after 10...", after 10 what?
Im assuming that if was just a typo.
Here's the code for the program. All you need to do is figure out how to stop asking once it the vote count is greater than or equal to 10. You learn and retain information best when you struggle, trust me.
If you have any questions about the syntax used, feel free to drop a comment.
parties = ['PLD', 'PRM', 'PRD']
max_votes = 10
num_votes = 0
print('~'*40)
print(f'\n~ Today is election day!\n~ You have {vote_count} votes to use\n~ Use them wisely!\n')
print('~'*40)
print(f' Polical Parties: {parties[:]}')
print('~'*40,'\n')
"""
As declared above, "num_votes" is the variable that is being used to keep
track of how many votes the user has used so far.
The += operator adds the value of the variable on the right to the existing
value of the variable on the left. It would be the same as saying:
>>> num_votes = num_votes + PLD_votes
So, its just saving the number of votes used to the varible "num_votes".
"""
PLD_votes = int(input(f'\nHow many votes for "{parties[0]}": '))
num_votes += PLD_votes
num_votes = input(f'\nHow many votes for "{parties[1]}": ')
num_votes += PRM_votes
PRD_votes = input(f'\nHow many votes for "{parties[2]}": ')
vote_count += PRD_votes
print('Here are the results...\n')
print(f'{parties[0]}: {PLD_votes}\n{parties[1]}: {PRM_votes}\n{parties[2]}: {PLD_votes}')
"""
The use of "f" and "{}" within strings is a way of formating the string to return letters with variables in them.
Example: print(f'Number of votes: {num_votes}') *mind the 'f'*
Here, typing 'f' before the quotations tells the program that you are going to be using "{}" within the string. What goes inside of the curlies "{}" are variables that you want to print along with the string. I prefer this
There are many different ways of accomplishing this:
Concatenation:
>>> print('Number of votes' + num_votes)
Using %d ('d' for numbers; for variable which contain strings you would use '%s'):
>>> print('Number of votes %d')
There are more ways of doing it, I just prefer using {} because to me it seems more straightforward to read.
"""

How to delete a youngest person from a list with function?

I need a program that would let a person enter a person's name and his birth year (5 people only).
The information is written into two lists - one with names and the other with years.
Then the program needs to remove the youngest person (or youngest people).
The final result needs to be printed out in a .txt file.
This is what I have so far:
names = []
ages = []
def names_ages():
while True:
name_age = input("Enter your name and birth year: ")
name_age.split()
print(name_age)
I don't know if I'm going into the right direction or not, could somebody suggest something?
I am going to assume that you are expecting first name and the year to be separated by a space like so.
"andrew 1996"
if so, you are going to want to split the input on space (to have the first entry correspond to "andrew" and the second to correspond to "1996"
response = name_age.split(" ")
Now you can add these values to the arrays that you defined up above (or you could use a python dictionary which I think would be better suited for this problem) https://docs.python.org/2/tutorial/datastructures.html#dictionaries
names.append(response[0])
ages.append(int(response[1]))
You are going to have to decide when to stop accepting names, which you would put in your while loop condition(right now it is running forever) Perhaps wait until the user input is "stop" or something of that nature.
That should get you in the correct direction, comment if you have any questions
name = []
year = []
x=0
while x <3:
x += 1
user = name.append(raw_input("enter name"))
user_year = year.append(raw_input("enter DOB"))
o = []
for i in zip(year,name):
o.append(i)
o.sort()
o.remove(o[0])
print o
This might one from of the solutions from many possible.

Python Data Structure Selection

Let's say I have a list of soccer players. For now, I only have four players. [Messi, Iniesta, Xavi, Neymar]. More players will be added later on. I want to keep track of the number of times these soccer players pass to each other during the course of a game. To keep track of the passes, I believe I'll need a data structure similar to this
Messi = {Iniesta: 4, Xavi: 5 , Neymar: 8}
Iniesta = {Messi: 4, Xavi: 10 , Neymar: 5}
Xavi = {Messi: 5, Iniesta: 10 , Neymar: 6}
Neymar = {Messi: 8, Iniesta: 5 , Xavi: 6}
Am I right to use a dictionary? If not, what data structure would be better suited? If yes, how do I approach this using a dictionary though? How do I address the issue of new players being included from time to time, and creating a dictionary for them as well.
As an example, If I get the first element in the list, List(i) in the first iteration is Messi, how do i use the value stored in it to create a dictionary with the name Messi. That is how do i get the line below.
Messi = [Iniesta: 4, Xavi: 5 , Neymar: 8]
It was suggested I try something like this
my_dynamic_vars = dict()
string = 'someString'
my_dynamic_vars.update({string: dict()})
Python and programming newbie here. Learning with experience as I go along. Thanks in advance for any help.
This is a fun question, and perhaps a good situation where something like a graph might be useful. You could implement a graph in python by simply using a dictionary whose keys are the names of the players and whose values are lists players that have been passed the ball.
passes = {
'Messi' : ['Iniesta', 'Xavi','Neymar', 'Xavi', 'Xavi'],
'Iniesta' : ['Messi','Xavi', 'Neymar','Messi', 'Xavi'],
'Xavi' : ['Messi','Neymar','Messi','Neymar'],
'Neymar' : ['Iniesta', 'Xavi','Iniesta', 'Xavi'],
}
To get the number of passes by any one player:
len(passes['Messi'])
To add a new pass to a particular player:
passes['Messi'].append('Xavi')
To count the number of times Messi passed to Xavi
passes['Messi'].count('Xavi')
To add a new player, just add him the first time he makes a pass
passes['Pele'] = ['Messi']
Now, he's also ready to have more passes 'appended' to him
passes['Pele'].append['Xavi']
What's great about this graph-like data structure is that not only do you have the number of passes preserved, but you also have information about each pass preserved (from Messi to Iniesta)
And here is a super bare-bones implementation of some functions which capture this behavior (I think a beginner should be able to grasp this stuff, let me know if anything below is a bit too confusing)
passes = {}
def new_pass(player1, player2):
# if p1 has no passes, create a new entry in the dict, else append to existing
if player1 not in passes:
passes[player1] = [player2]
else:
passes[player1].append(player2)
def total_passes(player1):
# if p1 has any passes, return the total number; otherewise return 0
total = len(passes[player1]) if player1 in passes else 0
return total
def total_passes_from_p1_to_p2(player1, player2):
# if p1 has any passes, count number of passes to player 2; otherwise return 0
total = passes[player1].count(player2) if player1 in passes else 0
return total
Ideally, you would be saving passes in some database that you could continuously update, but even without a database, you can add the following code and run it to get the idea:
# add some new passes!
new_pass('Messi', 'Xavi')
new_pass('Xavi', 'Iniesta')
new_pass('Iniesta', 'Messi')
new_pass('Messi', 'Iniesta')
new_pass('Iniesta', 'Messi')
# let's see where we currently stand
print total_passes('Messi')
print total_passes('Iniesta')
print total_passes_from_p1_to_p2('Messi', 'Xavi')
Hopefully you find this helpful; here's some more on python implementation of graphs from the python docs (this was a fun answer to write up, thanks!)
I suggest you construct a two dimensional square array. The array should have dimensions N x N. Each index represents a player. So the value at passes[i][j] is the number of times the player i passed to player j. The value passes[i][i] is always zero because a player can't pass to themselves
Here is an example.
players = ['Charles','Meow','Rebecca']
players = dict( zip(players,range(len(players)) ) )
rplayers = dict(zip(range(len(players)),players.keys()))
passes = []
for i in range(len(players)):
passes.append([ 0 for i in range(len(players))])
def pass_to(f,t):
passes[players[f]][players[t]] += 1
pass_to('Charles','Rebecca')
pass_to('Rebecca','Meow')
pass_to('Charles','Rebecca')
def showPasses():
for i in range(len(players)):
for j in range(len(players)):
print("%s passed to %s %d times" % ( rplayers[i],rplayers[j],passes[i][j],))
showPasses()

Making a statistics program

I am trying to write a Python program that computes and prints the following :
the average score from a list of scores
the highest score from a list of scores
the name of the student who got the highest score.
The program starts by asking the user to enter the number of cases. For EACH case, the program should ask the user to enter the number of students. For each student the program asks the user to enter the student's name and marks. For EACH case the program reports the average marks, the highest marks and the name of the student who got the highest marks.
Also
If there are more than one person with the highest score in a CASE, the program should report the first occurrence only.
The average score and the highest score should have exactly 2 decimal places.
The output should be as in the sample program output.
What I have been trying so far is the following:
grade=[]
name_list=[]
cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
print('case',case)
number=int(input('Enter number of students: '))
for number in range (1,number+1):
name=str(input('Enter name of student: '))
name_list.append(name)
mark=float(input('Enter mark of student:'))
grade.append(mark)
highest= max (grade)
average=(sum(grade)/number)
high_name=grade.index(max(grade))
print('average',average)
print('Highest',highest)
print (high_name)
This is what i have deciphered so far. my biggest problem now is getting the name of the individual with the high score. Any thoughts and feedback is much appreciated. As with respect to the answer posted below, i am afraid the only thing i do not understand is the dictionary function but otherwise the rest does make sense to me.
This resembles an assignment, it is too specific on details.
Anyways, the official docs are a great place to get started learning Python.
They are quite legible and there's a whole bunch of helpful information, e.g.
range(start, end): If the start argument is omitted, it defaults to0
The section about lists should give you a head start.
numcases = int(input("How many cases are there? "))
cases = list()
for _ in range(numcases):
# the _ is used to signify we don't care about the number we're on
# and range(3) == [0,1,2] so we'll get the same number of items we put in
case = dict() # instantiate a dict
for _ in range(int(input("How many students in this case? "))):
# same as we did before, but skipping one step
name = input("Student name: ")
score = input("Student score: ")
case[name] = score # tie the score to the name
# at this point in execution, all data for this case should be
# saved as keys in the dictionary `case`, so...
cases.append(case) # we tack that into our list of cases!
# once we get here, we've done that for EVERY case, so now `cases` is
# a list of every case we have.
for case in cases:
max_score = 0
max_score_student = None # we WILL need this later
total_score = 0 # we don't actually need this, but it's easier to explain
num_entries = 0 # we don't actually need this, but it's easier to explain
for student in case:
score = case[student]
if score > max_score:
max_score = score
max_score_student = student
total_score += score
num_entries += 1
# again, we don't need these, but it helps to demonstrate!!
# when we leave this for loop, we'll know the max score and its student
# we'll also have the total saved in `total_score` and the length in `num_entries`
# so now we need to do.....
average = total_score/max_entries
# then to print we use string formatting
print("The highest score was {max_score} recorded by {max_score_student}".format(
max_score=max_score, max_score_student=max_score_student))
print("The average score is: {average}".format(average=average))

Python / linked list / dynamic / overloading

I haven't programmed in a year so I am a little rusty. I really want to incorporate a link list but I am having trouble remembering how the code works, and having to implement it in Python isn't helping.
I only have the Node Class set up so far. Apparently, I cant use overloaded constructors which is annoying...
Basically i want to write a program that prompts a user to enter X number of bucket. Each bucket will have an X amount of different color balls. The user will specify how many balls for each color.
I welcome any help!
class Node:
def __init__(self, bucketNumber ,colorONE, colorTWO,
colorTHREE, colorFOUR, colorFIVE ):
self.bucket = bucketNumber # index
self.color1 = colorONE # quantity
self.color2 = colorTWO # quantity
self.color3 = colorTHREE # quantity
self.color4 = colorFOUR # quantity
self.color5 = colorFIVE # quantity
def printN(bucketNum):
for i in range(0,bucketNum):
print(nodes[i].bucket, nodes[i].color1, nodes[i].color2, nodes[i].color3, nodes[i].color4, nodes[i].color5)
colors = []
nodes = []
count = []
bucketNum = int(raw_input("The are 2-5 buckets with 2-5 ball colors. Enter number of Buckets:"))
colorNum = int(raw_input("Enter number of Colors:"))
for i in range(0,colorNum):
colors.append(raw_input("Enter color: " + str(i+1) ))
for i in range(0,bucketNum):
for j in range(0,colorNum):
count.append((raw_input("How many "+ colors[j] +" balls in bucket " + str(i+1))))
nodes.append( Node(i+1, count[0], count[1], count[2], count[3], count[4]) )
del count[ 0:len(count) ]
for i in range(0,colorNum):
print colors[i],
print " "
printN(bucketNum)
You don't seem to have a question, but note that there is probably no need to use a linked list, unless your list will have many insertions AND be large (because of python list memory allocation; and I wouldn't assume that this was a problem until it showed up in profiling), or if you will have many insertions and deletes at the ends of the list.
In that case, python provides collections.deque which is a linked sequence.

Categories

Resources