Regarding Employee Record in python - python-3.x

I have been working in an employee program in python and I an facing difficulties
The out put should look like below
from array import *
arr = array("i", [])
n= (int(input("Enter the number of employee's: ")))
arr.append(n)
for i in range(1,n+1):
name = input("Enter the name of the employee %s: " %(i))
from array import *
salary = array("f", [])
x = int(input("Enter %s current salary: " %(name)))
arr.append(x)
from array import *
Q1 = array("f", [])
rating1 = int(input("Enter the rating %s received for Q1: " %(name)))
arr.append(rating1)
from array import *
Q2 = array("f", [])
rating2= int(input("Enter the rating %s received for Q2: " %(name)))
arr.append(rating2)
from array import *
Q3 = array("f", [])
rating3 = int(input("Enter the rating %s received for Q3: " %(name)))
arr.append(rating3)
from array import *
Q4 = array("f", [])
rating4 = int(input("Enter the rating %s received for Q4: " %(name)))
arr.append(rating4)
def totalrating():
totalrating = [rating1, rating2, rating3, rating4]
total = sum(totalrating)
return(total)
def overallrating():
overallrating = totalrating()/4
return(overallrating)
def display():
print(name, x, rating1, rating2, rating3, rating4, totalrating(), overallrating())
display()
My programs goes like
The Out put is only returning the second value not the first can you help me what needs to be done

Alright so there is a lot of cleanup to do here. I will point out the changes in code comments and try to further explain as needed.
# The multiple import of array are redundant and the way you are using this is actually
# wrong so it's not needed. So I am commenting out this one and then deleting the rest.
# from array import *
# Here you just need a basic list and not an instance of the array module.
# arr = array("i", []) <- old code for reference.
arr = []
n= (int(input("Enter the number of employee's: ")))
# I commented out this line because you don't ever access this element after you set it
# so you can just not set it at all.
# arr.append(n)
# Because we got rid of the append above we can loop from 0 to n instead of 1 to n+1
for i in range(0, n):
name = input("Enter the name of the employee %s: " %(i))
# These sub arrays is unnecessary and part of the problem
# salary = array("f", [])
salary = int(input("Enter %s current salary: " %(name)))
# So the way you are appending stuff is part of the problem.
# Let's remove all of these appends out and we can do them at the end of the loop
# arr.append(x)
rating1 = int(input("Enter the rating %s received for Q1: " %(name)))
rating2 = int(input("Enter the rating %s received for Q2: " %(name)))
rating3 = int(input("Enter the rating %s received for Q3: " %(name)))
rating4 = int(input("Enter the rating %s received for Q4: " %(name)))
# Here we can append a dictionary to the array with the data laid out how you want it.
arr.append({
'name': name,
'salary': salary,
'rating1': rating1,
'rating2': rating2,
'rating3': rating3,
'rating4': rating4,
})
# Note the display function is now passing in the employee info here.
def totalrating(employee):
# So this function can be modified a few ways
# Also don't name variables the same as functions. It can lead to name clashing issues.
'''
# This is the original code and I am leaving is for posterity.
totalrating = [rating1, rating2, rating3, rating4]
total = sum(totalrating)
return(total)
'''
'''
# Here is the first way it could be modified.
total_rating = [
employee['rating1'], employee['rating2'], employee['rating3'],
employee['rating4']
]
total = sum(total_rating)
return total
# not there is no need to put () around the return in python
'''
# Here is how I would modify it though.
rating_keys = ['rating1', 'rating2', 'rating3', 'rating4']
return sum([employee[rate] for rate in rating_keys])
# This can be rewritten in one line and since it's only used in one place it should be done there
# def overallrating():
# overallrating = totalrating()/4
# return(overallrating)
def display():
# Now that the array has been cleaned up we can go through the array and print it.
for employee in arr:
# Instead of calculating them in the print statement just make variables ahead of time
total = totalrating(employee)
# This whole function is a one liner that should just be done here.
overall_rating = total/4
print(
employee['name'], employee['salary'], employee['rating1'], employee['rating2'],
employee['rating3'], employee['rating4'], total, overall_rating
)
display()
This should output as you asked. Cleaned up without the comments and old code the final product is:
arr = []
n= (int(input("Enter the number of employee's: ")))
for i in range(0, n):
name = input("Enter the name of the employee %s: " %(i))
salary = int(input("Enter %s current salary: " %(name)))
rating1 = int(input("Enter the rating %s received for Q1: " %(name)))
rating2 = int(input("Enter the rating %s received for Q2: " %(name)))
rating3 = int(input("Enter the rating %s received for Q3: " %(name)))
rating4 = int(input("Enter the rating %s received for Q4: " %(name)))
arr.append({
'name': name,
'salary': salary,
'rating1': rating1,
'rating2': rating2,
'rating3': rating3,
'rating4': rating4,
})
def totalrating(employee):
rating_keys = ['rating1', 'rating2', 'rating3', 'rating4']
return sum([employee[rate] for rate in rating_keys])
def display():
for employee in arr:
total = totalrating(employee)
overall_rating = total/4
print(
employee['name'], employee['salary'], employee['rating1'], employee['rating2'],
employee['rating3'], employee['rating4'], total, overall_rating
)
display()

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()

Program: finding the percentage / hackerrank

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))

Value not printing from inputs in UDF

Could I know what's missing in my UDF , my brain is fried atm and couldn't figure out what went wrong.
import math
import numpy as np
CoP = input("Enter the Value 1: ")
Po = input("Enter the Value 2: ")
Rf = input("Enter the Value 3: ")
Ti = input("Enter the Value 4: ")
def Total():
Rf = Rf / 100
Ti = Ti/ 12
Total = CoP - (Po * np.e ** (-(Rf * Ti)))
print(Total)
return Total
~Brittany
You cant use the global vars directly inside the method
Either pass the vars as arguments or declare the vars as global inside the method
Edit~: Converted the str to float
Method 1
import numpy as np
CoP = float(input("Enter the Value 1: "))
Po = float(input("Enter the Value 2: "))
Rf = float(input("Enter the Value 3: "))
Ti = float(input("Enter the Value 4: "))
def Total(CoP, Po, Rf, Ti):
Rf = Rf / 100
Ti = Ti / 12
Total = CoP - (Po * np.e ** (-(Rf * Ti)))
print(Total)
return Total
Total(CoP, Po, Rf, Ti)
Method 2
CoP = float(input("Enter the Value 1: "))
Po = float(input("Enter the Value 2: "))
Rf = float(input("Enter the Value 3: "))
Ti = float(input("Enter the Value 4: "))
def Total():
global CoP, Po, Rf, Ti
Rf = Rf / 100
Ti = Ti / 12
Total = CoP - (Po * np.e ** (-(Rf * Ti)))
print(Total)
return Total
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]

Counting Grades to print

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.

Resources