Basically i have this code, and i need a specific output where i state the winner and his number of votes. I seem to have everything down with finding the max value but not it's key counterpart. The error is in my second to last output. Let me know what you guys think, it's probably an easy fix and thank you!!!
print()
print()
print()
import sys
fo = open(sys.argv[1], "r")
dic = {}
count = 0
winner = 0
print("Candidates".center(15), "Votes".rjust(10), "Percent".rjust(10))
print("==========".center(15), "=====".rjust(10), "=======".rjust(10))
for line in fo:
line = line[:-1]
x = line.split(" ")
names = (x[0]) + " " + (x[1])
votes = int(x[2]) + int(x[3]) + int(x[4]) + int(x[5])
dic[names] = votes
count = votes + count
if winner < votes:
winner = votes
for i in dic.keys():
percent = int((dic[i]/count)*100.00)
print (i.center(15),str(dic[i]).center(15),str(percent)+"%")
#Loop through every kid and find percentage,
print()
print("The winner is", "" , "with", winner, "votes!")
print()
print("Total votes polled:", count)
print()
print()
print()
import operator
dic = {'a':1000, 'b':3000, 'c': 100}
max(dic.items(), key=operator.itemgetter(1))[0]
Related
I am very new in programming so I need help in "cleaning up my code" if the code is a mess if not then please recommend some better commands that accomplish the same purpose of any line or multiple lines.
Here is my program.
import random
def random_num():
lower_bound = input("what is your lower bound: ")
upper_bound = input("What is your upper bound: ")
trials = input("How many time would you like to try: ")
random_number = random.randint(int(lower_bound),
int(upper_bound))
user_input = input(
"What is the number that I am thinking in the range "
+ lower_bound + "-" + upper_bound + " (only " + trials + " tries): ")
ending = "Thanks For Playing"
continue_game = "That's it. Do you want to continue the game?
(Yes/No): "
count = 0
while True:
answer = int(user_input)
if count == int(trials) - 1:
lost = input("Sorry you have lost " + continue_game).lower()
if lost in ["yes"]:
random_num()
else:
return ending
else:
if answer == random_number:
win = input(continue_game).lower()
if win in ["yes"]:
random_num()
else:
return ending
elif answer >= random_number:
user_input = input("The number is smaller than that: ")
else:
user_input = input("The number is bigger than that: ")
count += 1
print(random_num())
Basically i need to make a game im python that can have a arbitrarily number of people that alternatly answers a multiplication question. But my issue is that i dont know how to keep it running until i hit 30 points. Ive tried to use dict's where the key is the player name and the value is the score. But it stops after the script only has ran once. I tried with a while loop but it went on forever. please help!
import random as r
n = int(input("Insert number of players: "))
d = {}
for i in range(n):
keys = input("Insert player name: ")
#to set the score to 0
values = 0
d[keys] = values
#to display player names
print("Player names are:")
for key in d:
print(key)
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
break
I think this will work
winner = False
while not winner :
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
winner = True
break
This is my code:
Guess Song V2
import random
import time
def Game():
x = 0
#AUTHENTICATION
Username = input("What is your username?")
#Asking for an input of the password.
Password = str(input("What is the password?"))
#If password is correct then allow user to continue.
if Password == "":
print("User Authenticated")
#If not then tell the user and stop the program
elif Password != "":
print("Password Denied")
exit()
#GAME
#Creating a score variable
score=0
#Reading song names and artist from the file
read = open("Song.txt", "r")
songs = read.readlines()
songlist = []
#Removing the 'new line' code
for i in range(len(songs)):
songlist.append(songs[i].strip('\n'))
while x == 0:
#Randomly choosing a song and artist from the list
choice = random.choice(songlist)
artist, song = choice.split('-')
#Splitting the song into the first letters of each word
songs = song.split()
letters = [word[0] for word in songs]
#Loop for guessing the answer
for x in range(0,2):
print(artist, "".join(letters))
guess = str(input("Guess the song : "))
if guess == song:
if x == 0:
score = score + 3
break
if x == 1:
score = score + 1
break
#Printing score, then waiting to start loop again.
print("Your score is", score)
print("Be ready for the next one!")
score = int(score)
leaderboard = open("Score.txt", "a+")
score = str(score)
leaderboard.write(Username + ' : ' + score + '\n')
leaderboard.close()
leaderboard = open("Score.txt", "r")
#leaderboardlist = leaderboard.readlines()
Scorelist = leaderboard.readlines()
for row in Scorelist:
Username, Score = row.split(' : ')
Score = int(Score)
Score = sorted(Score)
leaderboard.close()
Game()
So this is my code, for the leaderboard feature in this game, I want to make the list (Which contain both string - Username, and Interger - Score) into descending order of score(Interger). It would look something like this:
Before:
Player1 : 34
Player2 : 98
Player3 : 22
After:
Player2 : 98
Player1 : 34
Player3 : 22
Anyone know who to do this?
scores = {}
for row in score_list:
user, score = row.split(':')
scores[user] = int(score)
highest_ranking_users = sorted(scores, key=lambda x: scores[x], reverse=True)
for user in highest_ranking_users:
print(f'{user} : {score[user]}')
So I have this project where it asks the user for the number of .txt files these files are titled 'day' and then the number in ascending order. The format of what's inside the code is a sport/activity(key) then a comma and the number of people doing the sport(value). What I want is it to give an output of all the sports from the text files and if the activity(key) is duplicated then it adds up the people doing it(value). And to top that all off I wanted the total people who were participating(all the values added together)
days = int(input("How many days of records do you have? "))
i = 0
list1 = []
d = {}
for i in range(days):
i += 1
file = 'day' + str(i)
f = open(file + '.txt')
a = []
for line in f:
line = line.replace(',' , ' ')
list1.append(line)
words = line.split()
d[words[0]] = words[1]
a.append[words[1]]
stripped_line = [s.rstrip() for s in d]
for key,value in d.items() :
print (key + "," + value)
print("In total:", a, "attendees.")
INPUT
User_input = 3
day1.txt
swimming,1000
fencing,200
athletics,600
gymnastics,1200
tennis,500
day2.txt
diving,600
swimming,1200
tennis,500
rugby,900
handball,500
hockey,2300
trampoline,200
day3.txt
swimming,400
gymnastics,1200
fencing,100
diving,400
tennis,600
rugby,600
EXPECTED OUTPUT
swimming: 2600
fencing: 300
athletics: 600
gymnastics: 2400
tennis: 1600
diving: 1000
rugby: 1500
handball: 500
hockey: 2300
trampoline: 200
In total: 13000 attendees.
CURRENT OUTPUT
swimming,400
fencing,100
athletics,600
gymnastics,1200
tennis,600
diving,400
rugby,600
handball,500
hockey,2300
trampoline,200
This is one approach using collections.defaultdict.
Ex:
from collections import defaultdict
days = int(input("How many days of records do you have? "))
result = defaultdict(int)
for i in range(days):
with open("day{}.txt".format(i)) as infile:
for line in infile:
key, value = line.strip().split(",")
result[key] += int(value)
for key,value in result.items():
print (key + "," + str(value))
print("In total: {} attendees.".format(sum(result.values())))
Hopefully this will be very simple all I need help with is getting a count of the letter grades and then printing them along with the list.
Here is my code:
def getScores():
f_obj = open("scores.txt", "r")
data = f_obj.readlines() #read file into a list of record strings
f_obj.close()
return data
def displayData(data):
print("Name Avg Grade")#print headings
for record in data:
name, ex1, ex2, ex3 = record.split()
exam1 = float(ex1)
exam2 = float(ex2)
exam3 = float(ex3)
avg = round(exam1 + exam2 + exam3) / 3
if avg >= 100:
letterGrade = "A"
elif avg >= 89:
letterGrade = "B"
elif avg >= 79:
letterGrade = "C"
elif avg >= 69:
letterGrade = "D"
elif avg >= 59:
letterGrade = "F"
Just above here is where im stuck I cannot figure out how to do a count with the certain letter grades.
print("%-10s %5s %5s" % (name, round(avg, 1), letterGrade))
print()
print(
def addStudent():
name = input("Enter student name: ")
ex1 = int("Enter Exam 1 grade: ")
ex2 = int("Enter Exam 2 grade: ")
ex3 = int("Enter Exam 3 grade: ")
return name + "\t" + ex1 + "\t" + ex2 + "\t" + ex3
def storeData(data):
f_obj = open("scores.txt", "w")
f_obj.writelines(data)
f_obj.close()
def main():
scoreData = getScores() # read data file into a list
while True:
print("""
Program Options
1.) Display Students.
2.) Add a new student:
3.) Exit Program """)
option = input("Enter option 1, 2, or 3: ")
if option == "1":
displayData(scoreData)
elif option == "2":
scoreData.append(addItem()) # add record string to our list
elif option == "3":
storeData(scoreData)
print("Good bye.")
break
else:
print("Not a valid entry. Please enter 1, 2, or 3.")
main() # start the program
Hint: you already know how to determine if a grade is an A, B, C, etc. So all you need to do is increment a counter at the same time.
For example, you'd add in something like this to count the number of A grades:
if avg >= 100:
letterGrade = "A"
numAs += 1
Then do the same thing for each other grade type. Since this appears to be homework, I'll let you figure out how to do all this. Most importantly, even though Python isn't strict about this, think about the correct place to declare the counter variables.
Once you've got that working, here's an "extra credit" assignment: see if you can do all that using just a single array.