Program: finding the percentage / hackerrank - python-3.x

I am using below python code:
n = int(input('enter the number:'))
student_marks = {}
for i in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input('enter the name:')
list_1 = list(student_marks[query_name])
no = len(l)
print(no)
s = sum(l)
print(s)
ss = s/no
print(ss)
But, i am getting an error while input the query_name during the run of code.
source: https://www.hackerrank.com/challenges/finding-the-percentage/problem

you can try to do
n = int(input('enter the number:'))
student_marks = {}
for i in range(n):
name, *line = input("enter name and scroe (spared by space): ").split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input('enter the name:')
list_1 = list(student_marks[query_name])
no = len(list_1)
print("the numer of scores {}".format(no))
s = sum(list_1)
print("The sum of all scores {}".format(s))
ss = s/no
print("The average score {}".format(ss))

if __name__ == '__main__':
n = int(input())
student_marks = {}
count = 0
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
for i in student_marks[query_name]:
count += i
average = count / len(student_marks[query_name])
print("%.2f" %average)

You can try this solution:
--------------------------
from decimal import Decimal
# Main function (like Java main() method)
if __name__ == '__main__':
# Taking number of times input will be taken from console and converting it into int type
n = int(input())
# creating an empty dictionary
student_marks = {}
# Iterate from: 0 to n-1 times
for _ in range(n):
# Taking the first argument as name and all other numbers inside line var
name, *line = input().split()
# Converting the numbers contained in line variable to a map then, converting into list
scores = list(map(float, line))
# Inserting into dictionary as key - value pair
student_marks[name] = scores
# Taking the student name from console and store into query_name
query_name = input()
# Fetch student marks using student name
query_scores = student_marks[query_name]
# Sum all the marks
total_scores = sum(query_scores)
# Find average of the marks
avg = Decimal(total_scores/3)
# print the average upto two decimal point
print(round(avg, 2))

Related

Is it possible to not have to replicate code for each iteration of the function

def math():
x = str('y')
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
print(a)
print(b)
print(c)
print(d)
x == str(input("Would you like to continue"))
math()
Hello I'm new to programming and I was just casually doing this to make an easy calculator for my homework assignment and I wanted to know instead of replicating the code for each variable if there was a way to do the math one time and just keep reassigning values to the variable for the math. This might be dumb a question and it's not serious or anything I just was curious if there are better way's to do this.
Comments and suggestions:
def math():
x = str('y')
'y' is a string, so there is no need to convert it to a string using str(). x = 'y' is sufficient.
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
DRY - don't repeat yourself.
Define a function which takes an input and returns the computed results:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
and call this function n times:
result_list = compute(4) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
ask user if they wish to continue:
x == input("Would you like to continue? ")
run your function:
math()
Conclusion:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
def math():
how_often = 4
answer = 'y'
while answer == 'y':
result_list = compute(how_often) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
answer == input("Would you like to continue? (y/n): ")
math()

name, *line = input().split() in here can i use *line as a list?

I was doing a question on python and i got "name, *line = input().split() " this line in the code section. Then i searched and found that this line grabs the rest of the input as a list. Now, i want to use *line as a list for my furthur code. I have two question here.
Is *line actual a list?
How Can i use it as a list for furthur calculation?
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
Annotated code:
if __name__ == '__main__':
n = int(input('Enter number of students: '))
student_marks = {}
for _ in range(n): # _ character ignores the value returned by the generator
# split on whitespace, first argument goes to name, remaining go to line
name, *line = input('Enter record(name mrks1 mrks2 ...): ').split()
# line is indeed a list
print(type(line))
# parse the list "line" containing strings into floats/real numbers
scores = list(map(float, line))
# add it to the student dictionary, with value in "name" as the key
student_marks[name] = scores
query_name = input()

Passing an individual element value to a list using function

I am trying to pass an value on an "Empty" list(myUniqueList = []) using a user- defined function,
where I need to design it in a manner that in case I passed a value that is already existing in my
"empty" list, that value will then be added or append to the other "empty" list(myLeftovers = [] ).
def append_1(value):
myUniqueList.append(value)
def append_2(value):
myLeftovers.append(value)
myUniqueList = []
myLeftovers = []
n = int(input("Enter number of elements: "))
for i in range(n):
value = input("Enter a value: ")
for item in myUniqueList:
if item == value:
append_2(value)
else:
append_1(value)
print(myUniqueList)
print(myLeftovers)
myUniqueList = []
myLeftovers = []
def append_1(value):
myUniqueList.append(value)
def append_2(value):
myLeftovers.append(value)
n = int(input("Enter number of elements: "))
for i in range(n):
value = input("Enter a value: ")
if not value in myUniqueList:
append_1(value)
else:
append_2(value)
print(myUniqueList)
print(myLeftovers)
This should be what you are looking for. If you write the code without the two functions i think is better. Hope this will be helpful!
myUniqueList = []
myLeftovers = []
n = int(input("Enter number of elements: "))
for i in range(n):
value = input("Enter a value: ")
if not value in myUniqueList:
myUniqueList.append(value)
else:
myLeftovers.append(value)
print(myUniqueList)
print(myLeftovers)

Python3 Calculate summation of while loop output

I just started with python3 and tried this idea of assigning number to alphabets and calculate the total.
Eg: if input is "Hi" my output should come "6" (H is 5 and I is 1 so total is 6)
I do not know how to sum the output of while loop output.
name = input("Enter Your name ")
name =name.upper()
name = list(name)
print(name)
items = {'A':'1', 'I':'1', 'J':'1', 'Q':'1','Y':'1',
'B':'2', 'K':'2', 'R':'2',
'C':'3', 'G':'3', 'L':'3', 'S':'3',
'D':'4', 'M':'4', 'T':'4',
'E':'5', 'H':'5', 'N':'5', 'X':'5',
'U':'6', 'V':'6', 'W':'6', 'O':'7', 'Z':'7', 'F':'8', 'P':'8', '.':'0'}
counter = 0
x = len(name)-1
while counter <=x:
names = name[counter]
if names in items:
new_name = (items[names])
else:
print('no')
name_int = int(new_name)
print(name_int)
counter = counter +1
This should work for you:
name = input("Enter Your name ")
name =name.upper()
name = list(name)
print(name)
items = {'A':'1', 'I':'1', 'J':'1', 'Q':'1','Y':'1',
'B':'2', 'K':'2', 'R':'2',
'C':'3', 'G':'3', 'L':'3', 'S':'3',
'D':'4', 'M':'4', 'T':'4',
'E':'5', 'H':'5', 'N':'5', 'X':'5',
'U':'6', 'V':'6', 'W':'6', 'O':'7', 'Z':'7', 'F':'8', 'P':'8', '.':'0'}
counter = 0
x = len(name)-1
total = 0
while counter <=x:
names = name[counter]
if names in items:
new_name = (items[names])
total += int(new_name)
else:
print('no')
counter += 1
print(total)
However, you can write your code in a more pythonic way:
name = input("Enter Your name ")
items = {'A':1, 'I':1, 'J':1, 'Q':1,'Y':1,
'B':2, 'K':2, 'R':2,
'C':3, 'G':3, 'L':3, 'S':3,
'D':4, 'M':4, 'T':4,
'E':5, 'H':5, 'N':5, 'X':5,
'U':6, 'V':6, 'W':6, 'O':7, 'Z':7, 'F':8, 'P':8, '.':0}
total = 0
for ch in name.upper():
total += items(ch) if ch in items else 0
print total

Finding the key of the max value in a dictionary

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]

Resources