Sure the extra "sort" on the 5 scores is not what any teacher wants but
the goal of the challenge is to challenge the programmer. Do you read in all
the data and do a sort on the scores then the final number? Or maybe as you
read in the data you do an insertion sort at O(n) and only have to sort the
final score for output? It is interesting to see everyone's approach to this
requirement and why the challenge asks for it.
Names are ambiguous as part of the challenge. I don't put any restriction
how the data gets in. If it can be handled with code great. Some will
hard code it. Some might use a database. Some might just read it from
console or a file and find they might need a way to make the input
unambiguous. I have added a "," to help with this on the input.
I think you're miscalculating Derek Zoolander's scores; if he only has three, his average is over 5, not over 3. He did terribly because he didn't show up for class.
Python solution with three possible outputs: HTML, Markdown, or console (using texttable). I wasn't able to figure out how to write a test for the decorator by itself, so I could use some help with that, even though the decorator is unnecessary in this case since it's only used once.
edit: In the previous version, it was specified to round up; now it specifies just round, so that's adjusted for
from bisect import bisect_left
from collections import OrderedDict
from enum import Enum
import argparse, re, sys
class Format(Enum):
console = 1
html = 2
markdown = 3
# This is an object instead of naive strings in Student because names are
# complicated and in the long run it's only a matter of time until the
# simple version doesn't work. This particular name is representative
# of the western Europe/American style of [Given Name] [Paternal Name]
class Name(object):
def __init__(self, first, last):
self.first = first
self.last = last
class GradeTiers(object):
def __init__(self, tiers):
self._tiers = tiers
self._sorted = False
def sort_before_run(func):
def inner(self, *args):
if not self._sorted:
tiers = list(self._tiers) # We need a copy since lists are
# passed reference and someone else
# might be depending on its order
tiers.sort(key=lambda item: item[0]) # Sort by the value
self._tiers = OrderedDict(tiers)
self._sorted = True
return func(self, *args)
return inner
@sort_before_run
def letter(self, percentile_grade):
return self._tiers[GradeTiers
.get_closest_percentage_key(percentile_grade,
self._tiers.keys())]
@staticmethod
def get_closest_percentage_key(percentile_grade, percentage_keys):
pos = bisect_left(percentage_keys, percentile_grade)
if pos >= len(percentage_keys):
return percentage_keys[-1]
else:
return percentage_keys[pos]
class GradeBook(object):
def __init__(self, grade_tiers):
self.students = set()
self._grade_tiers = grade_tiers
self.output_type_callbacks = {
Format.console : self.get_student_grades_console,
Format.html : self.get_student_grades_html,
Format.markdown : self.get_student_grades_markdown
}
def add(self, student):
self.students.add(student)
def get_number_of_assignments(self):
return max([len(student.sorted_scores()) for student in self.students])
def get_student_grades(self, output_type=Format.console):
return self.output_type_callbacks[output_type]()
def get_student_grades_console(self):
# Need to run 'pip install texttable' before using this
from texttable import Texttable
table = Texttable(max_width=0)
header = ['First Name', 'Last Name', 'Overall Average', 'Letter Grade']
alignment = ['l', 'l', 'c', 'c']
for i in xrange(1, self.get_number_of_assignments() + 1):
header.append('Score {0}'.format(i))
alignment.append('c')
table.add_row(header)
table.set_cols_align(alignment)
number_of_assignments = self.get_number_of_assignments()
for student in self.sorted_students():
grade_average = student.grade_average(number_of_assignments)
row = [student.name.first,
student.name.last,
grade_average,
self._grade_tiers.letter(grade_average)]
for score in student.sorted_scores():
row.append(str(score))
while len(row) < len(header):
row.append(None)
table.add_row(row)
return table.draw()
def get_student_grades_html(self):
import dominate
from dominate import tags
page = dominate.document(title='Final Grades')
with page:
with tags.table(border="1"):
number_of_assignments = self.get_number_of_assignments()
with tags.tr():
tags.th("First Name")
tags.th("Last Name")
tags.th("Overall Average")
tags.th("Letter Grade")
tags.th("Scores", colspan=str(number_of_assignments))
for student in self.sorted_students():
with tags.tr():
grade_average = student.grade_average(number_of_assignments)
tags.td(student.name.first)
tags.td(student.name.last)
tags.td(grade_average)
tags.td(self._grade_tiers.letter(grade_average))
for score in student.sorted_scores():
tags.td(score)
return str(page)
def get_student_grades_markdown(self):
number_of_assignments = self.get_number_of_assignments()
to_return = "First Name | Last Name | Overall Average | Letter Grade | {0} |\n"\
.format(' | '\
.join(['Score {0}'.format(i) for i in xrange(1, number_of_assignments + 1)]))
to_return += "-----------|-----------|-----------------|--------------|{0}|\n"\
.format('|'\
.join(['------'.format(i) for i in xrange(0, number_of_assignments)]))
for student in self.sorted_students():
grade_average = student.grade_average(number_of_assignments)
to_return += "{0} | {1} | {2} | {3} | {4} |\n"\
.format(student.name.first,
student.name.last,
grade_average,
self._grade_tiers.letter(grade_average),
' | '.join([str(score) for score in student.sorted_scores()]))
return to_return
def sorted_students(self):
number_of_assignments = self.get_number_of_assignments()
return sorted(self.students,
key=lambda student:
student.grade_average(number_of_assignments),
reverse=True)
@staticmethod
def parse(infile, grade_tiers):
lines = infile.readlines()
to_return = GradeBook(grade_tiers)
for line in lines:
to_return.add(GradeBook.parse_student(line))
return to_return
@staticmethod
def parse_student(line):
match = re.match(r'^([^,]+)\s*,(\s*\D+)+\s*(.*)', line)
first_name, last_name = match.group(1).strip(), match.group(2).strip()
scores = [float(x) for x in re.split(r'\s+', match.group(3).strip())]
return Student(Name(first_name, last_name), scores)
class Student(object):
def __init__(self, name, scores):
self.name = name
self.scores = scores
def grade_average(self, number_of_assignments=None):
if number_of_assignments is None:
number_of_assignments = len(self.scores)
# Specifically want to use floats to avoid integer rounding
return int(round(sum(self.scores)/float(number_of_assignments)))
def sorted_scores(self):
return sorted(self.scores)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Calculate students' grades for a semester.")
parser.add_argument('-i', '--input', action='store', default=None, dest='input', help='Input file to use. If not provided, uses stdin.')
parser.add_argument('-o', '--output', action='store', default=None, dest='output', help='Output file to use. If not provided, uses stdin.')
parser.add_argument('-f', '--format', action='store', default='console', dest='format', choices=[name.lower() for name, member in Format.__members__.items()], help='Format to output grades in.')
args = parser.parse_args()
args.format = Format[args.format]
# I considered getting cute and using division and ASCII math, but this
# way grade tiers can be set to whatever
tiers = GradeTiers([(59, 'F'),
(62, 'D-'),
(65, 'D'),
(69, 'D+'),
(72, 'C-'),
(75, 'C'),
(79, 'C+'),
(82, 'B-'),
(85, 'B'),
(89, 'B+'),
(92, 'A-'),
(100, 'A')])
with (open(args.input) if args.input is not None else sys.stdin) as infile:
with (open(args.output, 'w') if args.output is not None else sys.stdout) as outfile:
grade_book = GradeBook.parse(infile, tiers)
outfile.write(grade_book.get_student_grades(args.format))
outfile.write("\n")
It's under parse_student, a staticmethod of GradeBook.
match = re.match(r'^([^,]+)\s*,(\s*\D+)+\s*(.*)', line)
first_name, last_name = match.group(1).strip(), match.group(2).strip()
If you're not familiar with regular expressions, they are a useful tool, but you have to be careful using them--there's a famous quote from Jamie Zawinski, "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." and it's not too far off the mark.
What that code says is start at the beginning of the line ("^"), then consider a group (the parenthesis create groups); this group must contain at least one non-comma character ("[^,]+" where "[^xxxx]" means "anything but x" and the follow-up "+" means "one or more of). That group gets stored in match.group(1) because it's the first group. From there, find any number of whitespace characters, then a comma ("\s*," "\s" is whitespace and "*" means "zero or more of"). Now consider another group. This group must contain zero or more spaces and at least one non-digit character ("\s*\D+"). That group must repeat one or more times (the "+" after "(\s*\D+)"). That group gets stored in match.group(2) because it's the second group. Next look for any number of whitespace ("\s*"). Now find zero or more anythings (".*" for clarity this should have been written as "(\d+\s+)*" instead, but because we've guaranteed digits from consuming anything that isn't a digit it'll be fine. Store that in match.group(3).
Does that help clarify things? Or at least introduce you to a new, arcane world?
I didn't notice the problem input had been updated to include helpful commas. Thanks for the explanation, though that regexp line noise voodoo should be banned :P
Regular expressions are how you deal with text in a concise, standardized, unambiguous manner. Realize that it took a full paragraph to explain one line of code, but people who are familiar with regexes could do all of that in their head. Regular expressions are extremely practical for parsing any regular text stream, which most of the /r/DailyProgrammer challenges involve. Ignoring their existence means artificially limiting your abilities; it's no different than deciding you're only going to write solutions in Assembly or the like. On top of that, it means the next reader has piece apart what a Turing-complete system is doing, which is always more difficult than dealing with something that's only regular, and rely on custom code instead of robust code, which is always risky.
Oh, I thought that name sounded familiar. And, yes, I have little idea what's going on in your solution. Except I think you may have mismatched quotes and I can see the F+ to F conversion.
functions in J are operators like + in other languages, that take arguments on right and maybe left. basic functions (verbs) take noun (data) arguments and produce noun/data results. adverbs take one left argument that may be a verb (function), and conjunctions take 2 arguments which may both be verbs.
One of the key concepts in J is a fork which is 3 or more verbs (f g h) where f and h will operate on the data parameters to the function (fork), and then g will be called with those 2 results to make the final result. A 5 verb fork (f2 g2 f g h) will take the results from f2 and g, and send them to g2 operator for the final result.
Though operators take only one right and left argument, those arguments can be lists or multidimensional tables.
One of the first lines in my program is (+/ % #) which is a fork translated as (sum divide count). / is a cool adverb called insert that modifies its argument + such that +/ 2 3 5 is equivalent to 2 + 3 + 5.
(....)@:(+/ % #) means compose, and the fork to the left of @: will then use mean as its argument. That fork computes the letter grade on the right, and the +- on the left, and joins the 2.
60 70 80 90&<:"1 0 ] 72 84
1 1 0 0 1 1 1 0
compares whether each of the right arguments is greater or equal to the left arguments producing a 1 for all that are true in a row for each of the right arguments. For each row, it is summed to produce a number from 0 to 4, and that number is used to index 'ABCDF'
' ' are the quote symbol in J. " is a conjunction called rank that lets you specify the chunking process of a verb. ("1 0) says to use lists as the left side argument and scalars (each atom) on the right side.
SQL, with a bit of Perl to massage the input. I'll be using SQLite's flavor of SQL to generate the report.
I created two tables with a many-to-one relationship to model the data.
students: lists all of the students without their scores
scores: lists all of the scores with a foreign key on students
For simplicity, I'm assuming last names are unique so that I can use them as a primary key.
-- Table of all students
CREATE TABLE students (last PRIMARY KEY, first);
-- Table of all scores for all students
CREATE TABLE scores (last REFERENCES students(last), score);
I also create a totalsview on a [JOIN](http://en.wikipedia.org/wiki/Join_(SQL)) between these two tables. Joins are the bread and butter of relational databases. This view will look and feel just like a normal table, and it will always be up to date. Later on this will make queries involving averages much simpler because we can join with this view.
-- Create a running averages "table"
CREATE VIEW totals AS
SELECT last, CAST(avg(score) AS INTEGER) AS total
FROM students NATURAL JOIN scores
GROUP BY last;
I also create a table grades for letter grades. I can join with this table in my report to get a letter grade column.
Before I can make any use of the data, it must be converted into SQL INSERT statements. This Perl script will do that.
#!/usr/bin/env perl
while (<>) {
my ($first, $last, @s) =
m/([a-zA-Z ]+?) +, +([a-zA-Z ]+?) +(\d+) +(\d+) +(\d+) +(\d+) +(\d+)/;
print "INSERT INTO students (first, last) VALUES ('$first', '$last');\n";
for (my $i = 0; $i < 5; $i++) {
print "INSERT INTO scores (last, score) VALUES ('$last', $s[$i]);\n";
}
}
The output looks like this,
INSERT INTO students (first, last) VALUES ('Jennifer', 'Adams');
INSERT INTO scores (last, score) VALUES ('Adams', 100);
INSERT INTO scores (last, score) VALUES ('Adams', 70);
INSERT INTO scores (last, score) VALUES ('Adams', 85);
INSERT INTO scores (last, score) VALUES ('Adams', 86);
INSERT INTO scores (last, score) VALUES ('Adams', 79);
INSERT INTO students (first, last) VALUES ('Bubba', 'Bo Bob');
INSERT INTO scores (last, score) VALUES ('Bo Bob', 50);
-- ...
The tables are in place so now I can generate a report. This involves joining all of the tables above. A natural join means that when the column names match (last in this case) we can join wherever they hold equivalent values. To get a letter grade, I also join on the grades table using <= and > operators to join on the correct grade letter.
SELECT first, last, total, grade
FROM totals
NATURAL JOIN students
JOIN grades ON total >= min AND total < max
ORDER BY total DESC, last ASC;
The output:
Tyrion Lannister 95 A
Kirstin Hill 94 A
Jaina Proudmoore 94 A
Katelyn Weekes 93 A
Arya Stark 91 A-
Opie Griffith 90 A-
Clark Kent 90 A-
Richie Rich 88 B+
Steve Wozniak 87 B+
Casper Ghost 86 B
Jennifer Adams 84 B
Derek Zoolander 84 B
Matt Brown 82 B-
Bob Martinez 82 B-
William Fence 81 B-
Jean Luc Picard 81 B-
Alfred Butler 80 B-
Valerie Vetter 80 B-
Ned Bundy 79 C+
Ken Larson 77 C+
Sarah Cortez 74 C
Wil Wheaton 74 C
Harry Potter 73 C
Stannis Mannis 72 C-
John Smith 70 C-
Jon Snow 70 C-
Tony Hawk 64 D
Bubba Bo Bob 49 F
Hodor Hodor 47 F
Edwin Van Clef 47 F
Unfortunately I'm still too much of a SQL newb to figure out how to list all of the scores in order in additional columns. There's probably some trick involving five left outer joins or something. I'm still working on that part.
This may seem a little bulky for such a small report, but it would scale up enormously well. After adding a few indexes in the right places, you could do all sorts of concurrent, fast queries in involving millions of students with thousands of scores each while safely making updates to the database at the same time.
Look into pivot/pivot tables; you're going to end up with an inline query. I think SQLite can't do it, which is all I can access right now, but that should be enough to get you started.
I'm going to show you something, but you have to promise never to do this in production code. Chances are you wouldn't, considering your medals, but still; I've seen this kind of thing in the wild. It made me regret accepting the job offer.
For production, use a real database where you can pivot instead of this ugliness. I sincerely hope there's a better way to do this in SQLite, but here's a hack that does work, but should never be deployed due to unmaintainability. It's largely influenced by this post.
SELECT students.first, students.last, total, grade, score_1, score_2, score_3, score_4, score_5
FROM totals
NATURAL JOIN students
JOIN (SELECT last, min(score) AS score_1 FROM scores GROUP BY last) s1 ON s1.last = students.last
JOIN (SELECT last, max(score) AS score_2
FROM (
SELECT last, score
FROM scores
WHERE (
SELECT count(*) FROM scores AS s
WHERE s.last = scores.last AND s.score < scores.score
) <= 1
)
GROUP BY last) s2 on s2.last = students.last
JOIN (SELECT last, max(score) AS score_3
FROM (
SELECT last, score
FROM scores
WHERE (
SELECT count(*) FROM scores AS s
WHERE s.last = scores.last AND s.score < scores.score
) <= 2
)
GROUP BY last) s3 on s3.last = students.last
JOIN (SELECT last, max(score) AS score_4
FROM (
SELECT last, score
FROM scores
WHERE (
SELECT count(*) FROM scores AS s
WHERE s.last = scores.last AND s.score < scores.score
) <= 3
)
GROUP BY last) s4 on s4.last = students.last
JOIN (SELECT last, max(score) AS score_5 FROM scores GROUP BY last) s5 ON s5.last = students.last
JOIN grades ON total >= min AND total < max
ORDER BY total DESC, totals.last ASC;
...
I have to shower now. Maybe forever. But yes, it can be done. Definitely shouldn't be, not like this. But it can be.
So you're indexing the scores by counting how many scores are smaller than it. That's awesome! I was thinking of about using LIMIT and OFFSET to do this, but I saw I was starting to craft a monstrosity and stopped. But you ... you were so preoccupied with whether you could that you didn't stop to think if you should!
Today I move closer to being able to empathize with J. Robert Oppenheimer. I swear my code's not usually that ugly, but that's what happens when you have to work around the limitations of your tools.
I tried to use LIMIT and OFFSET at first, but I couldn't figure out how to coordinate it with GROUP BY, so I poked around and figured that awfulness out.
This is evidence that "If it's stupid, but works, it isn't stupid" isn't always correct.
Having slept on this, I've discovered another approach. First, I wasn't putting all the information I had in the database! The order of the scores is information. As-is the scores table not only allows repeated rows, it requires it. This is not 3NF and violates one of the core parts of database theory. The correct way to enter the scores is to include a test ID (0-4), with the primary key being the tuple (last, testid).
When I insert the scores, I include the testid (0-4). This allows me to make a nice join to put each test in a column.
SELECT students.first, students.last, total, grade,
s0.score, s1.score, s2.score, s3.score, s4.score
FROM totals
NATURAL JOIN students
JOIN grades ON total >= min AND total < max
JOIN scores AS s0 ON s0.last = totals.last AND s0.testid = 0
JOIN scores AS s1 ON s1.last = totals.last AND s1.testid = 1
JOIN scores AS s2 ON s2.last = totals.last AND s2.testid = 2
JOIN scores AS s3 ON s3.last = totals.last AND s3.testid = 3
JOIN scores AS s4 ON s4.last = totals.last AND s4.testid = 4
ORDER BY total DESC, totals.last ASC;
However, this does't solve the sort problem. These are sorted by testid, not score. But if I make a view that covers this, I can use basically the same query, replacing testid with rank. I'm using your sort trick.
CREATE VIEW score_ranks AS
SELECT (SELECT count(s.score)
FROM scores AS s
WHERE s.last = scores.last AND s.score < scores.score) AS rank,
last, score
FROM scores;
And finally we get a much more manageable query that fulfills the original requirements.
SELECT students.first, students.last, total, grade,
s0.score, s1.score, s2.score, s3.score, s4.score
FROM totals
NATURAL JOIN students
JOIN grades ON total >= min AND total < max
JOIN score_ranks AS s0 ON s0.last = totals.last AND s0.rank = 0
JOIN score_ranks AS s1 ON s1.last = totals.last AND s1.rank = 1
JOIN score_ranks AS s2 ON s2.last = totals.last AND s2.rank = 2
JOIN score_ranks AS s3 ON s3.last = totals.last AND s3.rank = 3
JOIN score_ranks AS s4 ON s4.last = totals.last AND s4.rank = 4
ORDER BY total DESC, totals.last ASC;
Result (partial):
Tyrion Lannister 95 A 91 93 95 97 100
Kirstin Hill 94 A 90 92 94 95 100
Jaina Proudmoore 94 A 90 92 94 95 100
...
Bubba Bo Bob 49 F 30 50 53 55 60
Hodor Hodor 47 F 33 40 50 53 62
Edwin Van Clef 47 F 33 40 50 55 57
I believe it's basically the same as yours, but the view removes most of the redundancy. I imagine it would also be faster because the database engine will only compute the view once for the whole query.
Awesome! I recently learned about databases too. My submission uses MongoDB (nosql!). The way you created the letter grade column is awesome. I don't have that in my database, only my python output.
First, I like the fact that you used sql instead of something just programmy.
Couple thoughts.
I like to have a studentid column, which allows you to join scores against the id, instead of last name. This allows you to support multiple students with the same last name.
CREATE TABLE students
(
studentid serial NOT NULL,
lastname character varying,
firstname character varying,
CONSTRAINT student_pk PRIMARY KEY (studentid)
)
Using the serial datatype makes the column start at 1, and then automatically increment as you insert values.
Then the following nested query will group up the scores into a column called scorelist: (fyi: this is pgsql)
SELECT
students.studentid,
students.firstname,
students.lastname,
array_agg(scores.score order by score desc) as scorelist,
avg(scores.score)
FROM scores, students
WHERE students.studentid = scores.studentid
GROUP BY students.studentid;
I've been wrangling with Mathematica at work for a couple years now. I still struggle with the syntax of it. So here's a Mathematica front end to the pgsql database that does all the sorting and averaging.
Basically the final sort command Makes a table: the first element is the Firstname Lastname, second is the average score to 3 decimal places, then a List of the scores which has been sorted. Because the list came in as a list of 1-element-sets, that's why I called Flatten.
Then the "#1[[2]] > #2[[2]]" says that we want to use the second column as the sort criteria.
I think there's an error in the problem description; it currently reads
Those scoring in the top 3 percent of the rank get a "+" added. Those scoring in the lower 3 percent of the rank get a "-". However there is no "+" for an A and there are no "+" or "-" for an F grade.
student scoring 83% would be a B-
However, the lower 3 percent of B would be [80, 81, 82], so 83% should be a B. That or it should be the lower 4 percent and either the lower 3 percent or lower 4 percent.
I cheated a little bit. The text file in the challenge was really frustrating, so I fixed it to suit my needs better. Like so:
Jennifer,Adams,100 70 85 86 79
It was pretty easy to get that text file into another Mongo database. My program that did that calculated the grade (rounding, etc). I won't include that, though.
I guess I'll post my program that loads the database too:
from pymongo import MongoClient
import sys
def round(grade):
tmp = int(grade)
if grade - tmp >= .5:
return tmp + 1
return tmp
db = MongoClient().dailyprogrammer
infile = open(sys.argv[1], "r")
for line in infile:
split = line.split(",")
fn = split[0]
ln = split[1]
grades = split[2].split()
for i in range(5):
grades[i] = int(grades[i])
total = 0
for num in grades:
total += num
average = total / 5
average = round(average)
db.students.update(
{"lastname": ln, "firstname": fn},
{
"lastname": ln, "firstname": fn, "grades": grades,
"average": average
}, True)
print("Finished loading database...")
nice final grade function. IMO, short clever solutions are much more maintainable (even if less readable) than those that list 60 62 67 70 72 77 80 82 87 90 92, because the rules for grades could change, and the fewer lines/tokens you have, the fewer changes need to be made.
Haven't seen Scala yet so I thought I'd give it a try. I'm not very good with pattern matching yet, so the letter grade part might by more verbose than it needed to be. I'm also still a beginner in regex.
F#. did a tweak to the input to make it easier to split and parse using a regex. my exception handling leaves something to be desired.
open System.Text.RegularExpressions
let splitLines (s:string) =
List.ofSeq(s.Split([|'\n'|]))
let fmt = new Regex(@"[a-z]\ +\d")
let mutable students = []
for i in [1..100] do
try
let line = System.Console.ReadLine()
let L = fmt.Split line |> List.ofArray
let scores = L.Tail.Head
let name = Regex.Replace(L.Head, @" *, *", " ")
let grade = scores.Split(' ')
|> List.ofArray
|> List.filter ( fun x -> x.Length > 1 )
|> List.map ( fun x -> float(x) )
|> List.average
|> int
let letter =
match grade with
| n when n >= 90 -> "A"
| n when n >= 80 -> "B"
| n when n >= 70 -> "C"
| n when n >= 60 -> "D"
| _ -> "F"
let letter =
match grade%10 with
| m when m <= 3 && grade >= 60 && grade < 100 -> letter + "-"
| p when p >= 7 && grade <= 100 -> letter + "+"
| _ -> letter
let output = System.String.Format("{0} ({1}%) ({2}): {3}", name.PadRight(15), grade.ToString(), letter.PadRight(2), scores)
students <- ( grade, output ) :: students
with
| _ -> System.Console.Write("")
students
|> List.sort
|> List.rev
|> List.map ( fun(_,x) -> x )
|> List.iter ( fun x -> printf "%s\n" x )
0
Had me confused when the word "percentile" was used. In statistics, this means how many people you did better than so if you're in the 90'th percentile, you did better than 90% of the rest of the population. Here, percentile isn't really what is used but just a percentage of total grade.
public class FinalGradesSolver
{
private static readonly char[] MpPctToLetter =
{
'F', 'F', 'F', 'F', 'F', 'F', 'D', 'C', 'B', 'A', 'A'
};
private class Student
{
internal string First { get; private set; }
internal string Last { get; private set; }
internal List<int> Grades { get; private set; }
internal int Percentile
{
get { return (int)(Grades.Sum() / 5.0 + 0.5); }
}
internal string LetterGrade
{
get
{
var letter = MpPctToLetter[Percentile / 10];
var lastDigit = Percentile % 10;
var modifier = ' ';
if (lastDigit < 3 && letter != 'F')
{
modifier = '-';
}
else if (lastDigit >= 7 && letter != 'A' && Percentile >= 57)
{
modifier = '+';
}
return string.Format("{0}{1}", letter, modifier);
}
}
public Student(List<int> grades, string first, string last)
{
Grades = grades;
First = first;
Last = last;
}
}
readonly List<Student> _students = new List<Student>();
public FinalGradesSolver(StringReader stm)
{
string nextLine;
char[] digitStart = "123456789".ToCharArray();
while ((nextLine = stm.ReadLine()) != null)
{
var commaPos = nextLine.IndexOf(',');
var numPos = nextLine.IndexOfAny(digitStart);
var first = nextLine.Substring(0, commaPos - 1);
var last = nextLine.Substring(commaPos + 1, numPos - commaPos - 2).Trim();
var grades = nextLine.
Substring(numPos).
Split(' ').
Where(c => c != string.Empty).
Select(int.Parse).
ToList();
grades.Sort();
_students.Add(new Student(grades, first, last));
}
_students.Sort((s1, s2) => s2.Percentile.CompareTo(s1.Percentile));
}
public string ReportGrades()
{
var sb = new StringBuilder();
foreach (var student in _students)
{
// Rich Richie (88%) (B+): 86 87 88 90 91
sb.Append(string.Format("{0,-20}({1}%) ({2}): {3} {4} {5} {6} {7}",
student.First + " " + student.Last,
student.Percentile,
student.LetterGrade,
student.Grades[0],
student.Grades[1],
student.Grades[2],
student.Grades[3],
student.Grades[4]) + Environment.NewLine);
}
return sb.ToString();
}
}
The last record in the challenge input only has 3 grades; I'm going to assume this is a mistake and add 2 other results. Also, in the name inputs Edwin Van Clef and Jean Luc Picard how should the program differentiate between the surnames and last names? I'll resolve that ambiguity by putting underscores in the names to join them for the input because otherwise it could be either.
Anyway, here it is, in good old Ruby and some minor map-reduce abuse. It will right-align them all correctly using spaces.
Roughly a third of my implementation is just handling the formatting of output, though admittedly I did implement three different ways to do it. So don't worry too much about that taking a lot.
In Scala, throw expression returns Nothing, which is a subclass of everything, so you can do this:
val file = if (args.length == 2) new File(/* ... */)
else throw new IllegalStateException("invalid input")
This way it is possible to have immutable value with conditional initialization, though using Option is probably still better. Is this possible in Rust?
yes, that's possible: you can do let file;, assign it in one branch and then fail in the other. However file objects need to be mutable to read or write from them. In fact it would still be an error to not fail on the second branch, because file could be used uninitialised.
I'm self-taught and new, so feedback is extremely appreciated.
ETA sample output and fixed the +/- cutoffs.
class School(object):
def __init__(self, name, motto, mascot, students):
self.name = name
self.motto = motto
self.mascot = mascot
self.students = self.studgen(students)
self.grademodel = self.gradegen()
def studgen(self, text):
"""Add Students to the School."""
studlist = []
for student in text:
studlist.append(Student(student, text[student]))
return studlist
def gradegen(self):
"""Creates a letter-grading model."""
grades = 'ABCDF'
grademodel = []
max = 100
min = 90
plus = minus = False
for grade in grades:
grademodel.append(Grade(grade, max, min, plus, minus))
if max == 100:
max = max - 11
else:
max = max - 10
if min > 60:
min = min - 10
plus = max - 2
minus = min + 2
else:
min = 0
plus = minus = False
return grademodel
def show_students(self):
"""Prints a list of Students in the School."""
for student in self.students:
print student.name
def get_letters(self):
"""Prints all Students and their grades."""
letter = ''
for student in self.students:
for grade in self.grademodel:
if student.avgscore() >= grade.min and student.avgscore() <= grade.max:
letter = grade.name
if student.avgscore() >= grade.plus:
letter += '+'
if student.avgscore() <= grade.minus:
letter += '-'
print "%s: %s (%s%%) - Scores: %s" % (student.name, letter, \
student.avgscore(), \
" ".join(map(str, student.scores)))
letter = ''
class InputText(object):
def __init__(self, text):
self.text = self.cleanup(text)
def cleanup(self, text):
"""Turns raw text into a dictionary for
easier parsing later on."""
self.text = self.lines(text)
key = ''
value = []
cleantext = {}
for line in self.text:
line = self.singlespace(line)
for char in line:
key += char
try:
int(char)
key = self.name_parse(key[:-2])
cleantext[key] = line
key = ''
except ValueError:
pass
del cleantext['']
for line in cleantext:
cleantext[line] = self.get_int(cleantext[line])
return cleantext
def lines(self, text):
"""Turns raw text into a list where each item
is a single line."""
line = ''
lines = []
for char in text:
line += char
if '\n' in line:
line = line.rstrip('\n')
lines.append(line)
line = ''
return lines
def singlespace(self, text):
"""Remove non-single spaces."""
text = text.strip()
text = text.replace(',', '')
lastchar = ''
for char in text:
if char == ' ' and lastchar == ' ':
text = text.replace(' ', ' ')
lastchar = char
return text
def name_parse(self, text):
"""Swap FirstName-LastName."""
text = text.split(' ')
text.reverse()
if text[0]:
text[0] = text[0] + ','
text = ' '.join(text)
return text
def get_int(self, text):
"""Turns integers in a line into
actual integers."""
text = text.split()
ints = []
for word in text:
try:
ints.append(int(word))
except:
pass
return ints
class Grade(object):
def __init__(self, name, max, min, plus, minus):
self.name = name
self.max = max
self.min = min
self.plus = plus
self.minus = minus
class Student(object):
def __init__(self, name, scores):
self.name = name
self.scores = sorted(scores)
def avgscore(self):
"""Returns a student's average score."""
totscore = 0
n = 0
for score in self.scores:
totscore += score
n += 1
return totscore / n
###################################################################
"""Create a cleaned version of the input text on Reddit."""
reddit = InputText("""Jennifer , Adams 100 70 85 86 79
Bubba , Bo Bob 50 55 60 53 30
Matt , Brown 72 82 92 88 79
Ned , Bundy 73 75 80 79 88
Alfred , Butler 80 90 70 100 60
Sarah , Cortez 90 72 61 70 80
William , Fence 88 86 83 70 79
Casper , Ghost 80 85 87 89 90
Opie , Griffith 90 90 90 90 90
Tony , Hawk 60 60 60 72 72
Kirstin , Hill 100 90 92 94 95
Hodor , Hodor 40 50 53 62 33
Clark , Kent 89 90 88 92 91
Tyrion , Lannister 93 97 100 91 95
Ken , Larson 70 80 85 73 79
Stannis , Mannis 60 70 75 77 78
Bob , Martinez 79 88 92 82 72
Jean Luc , Picard 90 89 95 70 65
Harry , Potter 73 75 77 69 73
Jaina , Proudmoore 90 92 100 95 94
Richie , Rich 88 90 87 91 86
John , Smith 90 80 70 60 50
Jon , Snow 70 70 70 70 72
Arya , Stark 91 92 90 93 90
Edwin , Van Clef 40 50 55 57 33
Valerie , Vetter 79 81 78 83 80
Katelyn , Weekes 90 95 92 93 97
Wil , Wheaton 70 80 75 71 77
Steve , Wozniak 88 89 87 86 85
Derek , Zoolander 80 81 85 88 90""")
###################################################################
"""Found the school and fill it with students."""
greendale = School('Greendale', 'E Pluribus Anus', 'Human Being', reddit.text)
"""View each students' performance."""
greendale.get_letters()
Just a very quick readthrough. Nothing that affects correctness, but regarding code style.
If you ever catch yourself using the pattern
output = []
for x in y:
output.append(x)
replace that with a list comprehension, or understand why you did not do so.
PEP8 says to use inline comments sparingly, but this is exactly the sort of place where an inline comment would help:
if max == 100:
max = max - 11
else:
max = max - 10
if min > 60:
min = min - 10
plus = max - 2
minus = min + 2
I had to work too much to understand what this does. If you hardcode 'magic' numbers, it's not bad to explain them inline
Couple PEP-8 things that continually distracted me, especially with how whitespaces were used around docstrings. Not a killer, but PEP8 and PEP257 are good things to follow.
Overall the code works (I assume!) but is not especially Pythonic. To pick out one example, this function could be streamlined so much:
def get_int(self, text):
"""Turns integers in a line into
actual integers."""
text = text.split()
ints = []
for word in text:
try:
ints.append(int(word))
except:
pass
return ints
I'd suggest rewriting this as a one-liner list comprehension as a fun learning exercise.
if you ever find yourself writing a class that is merely an attribute holder, consider using a namedtuple.
Namedtuples are one of my favorite Python structures. They are much more efficient than classes, and serve the purpose of holding named attributes just as well.
from collections import namedtuple
Grade = namedtuple('Grade', ('max', 'min', 'plus', 'minus'))
g = Grade(100, 87, False, False)
g = Grade(max=100, min=87, plus=False, minus=False)
print(g.max)
Namedtuples behave as regular tuples, so they can also be unpacked
Here is my submission in C#. This is the first time I'd ever used params, I was looking for a Regex that would collect any number of grades instead of just 5, so any comments there would be most appreciated.
Here is the main program:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace FinalGrades
{
public class Program
{
public static void Main(string[] args)
{
List<Student> students = new List<Student>();
FileStream inFile = new FileStream(args[0], FileMode.Open);
StreamReader sReader = new StreamReader(inFile);
while (!sReader.EndOfStream)
{
string line = sReader.ReadLine().Trim();
string[] studentLine = Regex.Split(line, @"^(\w+\s*\w+)\s*,\s*(\w+\s*\w+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$");
// wanted better regex that gets any number of grades
// then
// copy grades to int array to pass to constructor
Student student = new Student(studentLine[1], studentLine[2], Convert.ToInt32(studentLine[3]), Convert.ToInt32(studentLine[4]), Convert.ToInt32(studentLine[5]), Convert.ToInt32(studentLine[6]), Convert.ToInt32(studentLine[7]));
students.Add(student);
}
// close inputs
sReader.Close(); inFile.Close();
// students implements IComparable sorting reverse order of FinalGrade
students.Sort();
foreach (Student student in students)
{
Console.Write("{0} {1} ({2}%) ({3}):", student.LastName.PadRight(10), student.FirstName.PadRight(10), student.FinalGrade, student.FinalLetter);
student.Grades.Sort(); student.Grades.Reverse();
foreach (int grade in student.Grades)
Console.Write(" {0}", grade);
Console.WriteLine();
}
// wait for input to close console window
Console.ReadLine();
}
}
}
Here is the Student Class:
using System;
using System.Collections.Generic;
namespace FinalGrades
{
public class Student : IComparable
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int FinalGrade { get; set; }
public string FinalLetter { get; set; }
public List<int> Grades = new List<int>();
public Student(string firstName, string lastName, params int[] grades)
{
FirstName = firstName;
LastName = lastName;
foreach (int grade in grades)
Grades.Add(grade);
calculateFinalGrade();
calculateFinalLetter();
}
private void calculateFinalLetter()
{
if (FinalGrade > 93)
FinalLetter = "A";
else if (FinalGrade >= 90)
FinalLetter = "A-";
else if (FinalGrade >= 87)
FinalLetter = "B+";
else if (FinalGrade > 83)
FinalLetter = "B";
else if (FinalGrade >= 80)
FinalLetter = "B-";
else if (FinalGrade >= 77)
FinalLetter = "C+";
else if (FinalGrade > 73)
FinalLetter = "C";
else if (FinalGrade >= 70)
FinalLetter = "C-";
else if (FinalGrade >= 67)
FinalLetter = "D+";
else if (FinalGrade > 63)
FinalLetter = "D";
else if (FinalGrade >= 60)
FinalLetter = "D-";
else
FinalLetter = "F";
}
private void calculateFinalGrade()
{
double sum = 0.0;
foreach (int grade in Grades)
sum += grade;
FinalGrade = (int)Math.Round(sum / Grades.Count);
}
// sort highest grades first
public int CompareTo(object obj)
{
Student s = (Student)obj;
return s.FinalGrade - this.FinalGrade;
}
}
}
C#. Didn't read the Output section properly/didn't plan. So it doesn't order by best-> worst. Not the nicest code but... it's 3am and /bothered. Requires a text file with the input in it at the directory named 'Students.txt'
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace FinalGrades
{
class Program
{
static void Main()
{
var students = new List<string>();
students = LoadFile();
foreach (var student in students)
{
var split = student.Replace(" ", " ").Replace(" ", " ").Replace(" ", " ");
var scores = Regex.Split(split, @"\D+");
var totalScore = int.Parse(scores[1]) + int.Parse(scores[2]) + int.Parse(scores[3]) + int.Parse(scores[4]) + int.Parse(scores[5]);
var scorePercent = (int)Math.Round((double)(100 * totalScore) / 500);
var firstLast = String.Join(" , ", Regex.Replace(split, @"[\d-]", string.Empty).Split(',')).Replace(" , ", "").Replace(" ", " ").Trim();
var tabs = "\t\t";
var symbol = "";
var grade = "";
if (firstLast.Length > 15) tabs = "\t\t";
if (firstLast == "Jaina Proudmoore" || firstLast == "Tyrion Lannister") tabs = "\t";
if (scorePercent.ToString().EndsWith("1") || scorePercent.ToString().EndsWith("2") || scorePercent.ToString().EndsWith("3")) symbol = "-";
if (scorePercent.ToString().EndsWith("7") || scorePercent.ToString().EndsWith("8") || scorePercent.ToString().EndsWith("9")) symbol = "+";
if (scorePercent <= 59)
{
grade = "F";
symbol = "";
}
if (scorePercent >= 60 && scorePercent <= 69) grade = "D";
if (scorePercent >= 70 && scorePercent <= 79) grade = "C";
if (scorePercent >= 80 && scorePercent <= 89) grade = "B";
if (scorePercent >= 90 && scorePercent <= 97) grade = "A";
if (scorePercent >= 98 && scorePercent <= 100)
{
grade = "A";
symbol = "";
}
Console.WriteLine(firstLast.Replace(" , ", "").Trim() + tabs + "(" + scorePercent +"%) (" + grade + symbol + "):" + string.Format(" {0} {1} {2} {3} {4}", scores[1], scores[2], scores[3], scores[4], scores[5]));
}
Console.ReadKey();
}
static List<string> LoadFile()
{
var items = new List<string>();
string line;
if (File.Exists(Directory.GetCurrentDirectory() + @"\Students.txt"))
{
var file = new StreamReader(Directory.GetCurrentDirectory() + @"\Students.txt");
while ((line = file.ReadLine()) != null)
{
items.Add(line);
}
}
return items;
}
}
}
I know I'm probably annoying the shit out of you guys every time I post, but I am new to programming. Started with Java last September. I've been learning python over the past month. Please, please, PLEASE! point out any mistakes or bad practices in my code.
Python 2.7.7:
#-------------------------------------------------------------------------------
# Name: /r/DailyProgrammer Intermediate Challenge: Final Grades
# Purpose: proccess student grades and output them in specific
# manner
#
# Author: drogbfan
#
# Created: 19/06/2014
#-------------------------------------------------------------------------------
import math
def round_up_down(number):
if number % 1 >= .5:
return math.ceil(number)
else:
return math.floor(number)
def process_grade(grade):
number_grade = int(grade)
letter_grade = ""
if number_grade > 59 and number_grade < 70:
letter_grade = "D"
elif number_grade > 69 and number_grade < 80:
letter_grade = "C"
elif number_grade > 79 and number_grade < 90:
letter_grade = "B"
elif number_grade > 89 and number_grade <= 100:
if number_grade < 93:
letter_grade = "A-"
return letter_grade
else:
letter_grade = "A"
return letter_grade
else:
if number_grade > 56:
letter_grade = "F+"
return letter_grade
else:
letter_grade = "F"
return letter_grade
if number_grade - int(grade[0:1]+"0") > 6:
letter_grade += "+"
if number_grade - int(grade[0:1]+"0") < 3:
letter_grade += "-"
return letter_grade
def process_student(student_info):
info0 = student_info.split(" ")
info = []
for i in range(0, len(info0)):
if info0[i] != "" and info0[i] != "," and info0[i] != " ":
info.append(info0[i])
grade_sum = 0
grades_start_index = 0
if info[2].isdigit() == True:
grades_start_index = 2
for i in range(2, len(info)):
grade_sum += float(info[i])
else:
grades_start_index = 3
for i in range(3, len(info)):
grade_sum += float(info[i])
ordered_grades = []
for i in range(grades_start_index, len(info)):
ordered_grades.append(int(info[i]))
ordered_grades.sort()
average_grade = str(int(round_up_down(grade_sum / 5)))
letter_grade = process_grade(average_grade)
ordered_grades_string = str(ordered_grades)[
1:len(str(ordered_grades)) -1].replace(",","")
if grades_start_index == 2:
return "%-12s %-12s (%s) (%s):%-5s %s" % (info[1], info[0],
average_grade + "%", letter_grade,"", ordered_grades_string)
else:
return "%-12s %-12s (%s) (%s):%-5s %s" % (info[1] +" "+info[2], info[0],
average_grade + "%", letter_grade,"", ordered_grades_string)
test = open("6.18.2014.txt", "r")
print "%-12s %-12s %s %s %-5s %s\n" % ("Last name", "First name", "Avg.", "Mrk.","", "Scores")
for line in test:
print process_student(line)
My answer in Java. Feedback is always welcome. I have to be honest, I partly used the methode of using a pattern to generate my students from another reply.
package Challenge_167_Intermediate;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FinalGradeCalc{
private static final Pattern PATTERN = Pattern.compile("(.+)\\s+,\\s+(.+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+ (\\d+)");
public static List<Student> students = new ArrayList<Student>();
public static void main(String[] args){
FinalGradeCalc fgc = new FinalGradeCalc();
try{
fgc.readFile(new File("Path to my file"));
}catch(IOException e){
e.printStackTrace();
}
Collections.sort(students);
fgc.printAllStudents(students);
}
public void readFile(File file) throws IOException{
FileReader fr = new FileReader(file);
BufferedReader reader = new BufferedReader(fr);
String line = "";
while((line = reader.readLine()) != null){
Student s = genFromFile(line);
if(s != null) students.add(genFromFile(line));
}
reader.close();
}
public void printAllStudents(List<Student> students){
for(Student s : students){
System.out.println(s.toString());
}
}
public Student genFromFile(String line){
Matcher matcher = PATTERN.matcher(line);
if(!matcher.matches()) return null;
String firstName = matcher.group(1);
String lastName = matcher.group(2);
int[] grades = new int[5];
for(int i = 0; i < 5; i++){
grades[i] = Integer.parseInt(matcher.group(i + 3));
}
return new Student(firstName, lastName, grades);
}
private class Student implements Comparable<Student>{
public String firstName;
public String lastName;
public int[] grades = new int[5];
public int percentage;
public int total;
public String grade;
public Student(String firstName, String lastName, int[] grades){
this.firstName = firstName;
this.lastName = lastName;
this.grades = grades;
Arrays.sort(this.grades);
for(int i = 0; i < grades.length; i++) total += grades[i];
percentage = Math.round(total * 100 / 500);
grade = getGrade(percentage);
}
public String getGrade(int percentage){
if(percentage >= 90){
if(percentage > 92) return "A";
return "A-";
}else if(percentage >= 80){
if(percentage > 86) return "B+";
if(percentage < 83) return "B-";
return "B";
}else if(percentage >= 70){
if(percentage > 76) return "C+";
if(percentage < 73) return "C-";
return "C";
}else if(percentage >= 60){
if(percentage > 66) return "D+";
if(percentage < 63) return "D-";
return "D";
}else{
return "F";
}
}
@Override
public String toString(){
return String.format("%-10s %-11s %-4d %-3s %-3s %-3d %-3d %-3d %-3d %-3d", firstName, lastName, per centage, grade, ":", grades[0], grades[1], grades[2], grades[3], grades[4]);
}
@Override
public int compareTo(Student s){
return s.percentage - this.percentage;
}
}
}
Iterate through the lines and build a Student object to hold all the info:
Match match = Regex.Match(line, pattern);
List<int> grades = new List<int>();
for (int i = 3; i <= 7; i++)
{
grades.Add(Convert.ToInt32(match.Groups[i].Value));
}
Student student = new Student(match.Groups[1].Value, match.Groups[2].Value, grades);
students.Add(student);
Then iterate through, outputting the different values:
foreach (Student stu in students.OrderByDescending(x => x.FinalPercentage))
{
Console.WriteLine("{0} {1} {2} {3} {4}", stu.LastName, stu.FirstName, stu.FinalPercentage, stu.LetterGrade, stu.GradesInOrder);
}
The Student class has methods for determining the percentage and letter grade (expanded for clarity):
setFinalPercentage:
int sum = Grades.Sum();
int totalPossible = Grades.Count * 100;
var percentage = Math.Round(Convert.ToDouble(sum) / Convert.ToDouble(totalPossible), 2);
this.FinalPercentage = Convert.ToInt32(100 * percentage);
setLetterGrade (I'm sure there's an more elegant/easier way to do this):
int grade = FinalPercentage;
string result = "F";
if (grade >= 90)
{
result = "A";
if (grade <= 92)
result += "-";
}
else if (grade >= 80)
{
result = "B";
if (grade <= 82)
result += "-";
else if (grade >= 88)
result += "+";
}
else if (grade >= 70)
{
result = "C";
if (grade <= 72)
result += "-";
else if (grade >= 78)
result += "+";
}
else if (grade >= 60)
{
result = "D";
if (grade <= 62)
result += "-";
else if (grade >= 68)
result += "+";
}
this.LetterGrade = result;
GradesInOrder:
string result = String.Empty;
foreach (int grade in Grades.OrderBy(g => g))
{
result += grade + " ";
}
return result.Trim();
#! /usr/bin/env lua
local GradeBook = {}
-- remove trailing white space from string
-- from lua-users.org/wiki/CommonFunctions
local function rtrim(s)
local n = #s
while n > 0 and s:find("^%s", n ) do n = n - 1 end
return s:sub(1, n)
end
local function round(n)
return math.floor(n+.5)
end
function GradeBook.read_input()
local students = {}
for line in io.lines() do
local student = {}
-- input was difficult to read, and I still have to trim excess whitespace
pattern = "([%w%s]+)%s+,%s+([%a%s]+)%s+(%d*)%s+(%d*)%s+(%d*)%s+(%d*)%s+(%d*)"
firstname, lastname, g1, g2, g3, g4, g5 = line:match(pattern)
student.firstname, student.lastname = rtrim(firstname), rtrim(lastname)
student.grades = {tonumber(g1), tonumber(g2), tonumber(g3),
tonumber(g4), tonumber(g5)}
table.insert(students, student)
end
return GradeBook.find_averages(students)
end
function GradeBook.find_averages(students)
-- caclulate each students average and letter grade
for i = 1, #students do
local total = 0
for _, grade in pairs(students[i].grades) do
total = total + grade
end
students[i].average = round(total / #students[i].grades)
students[i].letter_grade = GradeBook.find_letter_grades(students[i].average)
end
return students
end
function GradeBook.find_letter_grades(grade)
-- Turn numeric grade into appropriate letter grade
if grade > 93 then return 'A'
elseif grade > 89 then return 'A-'
elseif grade > 86 then return 'B+'
elseif grade > 83 then return 'B'
elseif grade > 79 then return 'B-'
elseif grade > 76 then return 'C+'
elseif grade > 73 then return 'C'
elseif grade > 69 then return 'C-'
elseif grade > 66 then return 'D+'
elseif grade > 63 then return 'D'
elseif grade > 59 then return 'D-'
else return 'F'
end
end
function GradeBook.display(students)
-- All the data is caculated by the time this function is called,
-- the only thing left is to sort the data and display it
-- sort entire table from highest to lowest average grade
table.sort(students, function(a, b)
return (a.average > b.average)
end)
for i = 1, #students do
-- sort the grades of each individual student, lowest to highest
table.sort(students[i].grades, function(a, b) return (a < b) end)
io.write(string.format("%-12s %-10s (%2i%%) (%-2s):",
students[i].lastname,
students[i].firstname,
students[i].average,
students[i].letter_grade))
for _, grade in ipairs(students[i].grades) do io.write(' ' .. grade) end
io.write('\n')
end
end
local students = GradeBook.read_input()
GradeBook.display(students)
I feel like there should be a more concise way of solving this using metatables and closures, but I don't really see how. Any tips would be appreciated!
Here's my solution in Clojure. There is absolutely no error handling, so a proper input file is assumed.
Edit: To see a colorized version, view it at Github. It's much prettier in color.
(ns dailyprogrammer.final-grades
(:require [clojure.string :as string]))
(defn get-data-from-file
"Reads the data file, returning a vector of data for each line in the file."
[file-name]
(let [raw-contents (slurp file-name)
lines (string/split raw-contents #"\n")]
(map #(rest (re-find #"\s*(\w+)\s*,\s*([^0-9]+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)" %)) lines)))
(defn- string->int
"Use Java's Integer/parseInt to create ints from strings"
[str]
(Integer/parseInt str))
(defn- convert-scores-to-proper-type
"Convert all the scores from strings to ints."
[records]
(for [record records
:let [prefix (take 2 record)
scores (drop 2 record)]]
(concat prefix (map string->int scores))))
(defn- compute-grade-average
"Compute the mean of a student's grades"
[grades]
(let [sum (reduce + grades)
num (count grades)]
(Math/round (double (/ sum num)))))
(defn- between?
"Determines if the number is between two other numbers"
[num min max]
(and (>= num min)
(< num max)))
(defn- compute-plus-or-minus
"Decides if there should be a + or - with the letter grade.
A + for the top 30 percentile, and a - for the bottom 30."
[score letter]
(let [perc (rem score 10)
plus-or-minus (cond
(<= perc 2) "-"
(and (>= perc 7)
(not (= letter "A"))) "+"
:else "")]
(format "%s%s" letter plus-or-minus)))
(defn- compute-letter-grade
"Compute the correct letter grade for the student's average score"
[score]
(cond
(between? score 90 101) (compute-plus-or-minus score "A")
(between? score 80 90) (compute-plus-or-minus score "B")
(between? score 70 80) (compute-plus-or-minus score "C")
(between? score 60 70) (compute-plus-or-minus score "D")
:else "F"))
(defn- process-student
"Format the student naem and grade for display"
[student-info]
(let [[first-name last-name & grades] student-info
average (compute-grade-average grades)
letter-grade (compute-letter-grade average)
sorted-grades (sort grades)]
[first-name last-name average letter-grade sorted-grades]))
(defn- format-student
"Pretty-prints the data for each student"
[student-info]
(let [[first-name last-name average letter-grade grades] student-info
grades-str (apply (partial format "%3d %3d %3d %3d %3d") grades)]
(format "%-10s %-10s %3d%% %-2s %s" first-name last-name average letter-grade grades-str)))
(defn process-grades
"Process all the grade records from the specified file"
[file-name]
(let [data (get-data-from-file file-name)
records (convert-scores-to-proper-type data)
processed-students (map process-student records)
sorted-students (sort-by #((juxt second first) (drop 1 %)) processed-students)]
(map format-student (reverse sorted-students))))
(defn- print-grades
"Prints the grades after all the works is done"
[records]
(doseq [record records]
(println record)))
;; There is a test file at resources/final_grades.txt
(defn -main
[& args]
(print-grades (process-grades (first args))))
And here's the output
Tyrion Lannister 95% A 91 93 95 97 100
Jaina Proudmoore 94% A 90 92 94 95 100
Kirstin Hill 94% A 90 92 94 95 100
Katelyn Weekes 93% A 90 92 93 95 97
Arya Stark 91% A- 90 90 91 92 93
Clark Kent 90% A- 88 89 90 91 92
Opie Griffith 90% A- 90 90 90 90 90
Richie Rich 88% B+ 86 87 88 90 91
Steve Wozniak 87% B+ 85 86 87 88 89
Casper Ghost 86% B 80 85 87 89 90
Derek Zoolander 85% B 80 81 85 88 90
Jennifer Adams 84% B 70 79 85 86 100
Bob Martinez 83% B 72 79 82 88 92
Matt Brown 83% B 72 79 82 88 92
Luc Picard 82% B- 65 70 89 90 95
William Fence 81% B- 70 79 83 86 88
Valerie Vetter 80% B- 78 79 80 81 83
Alfred Butler 80% B- 60 70 80 90 100
Ned Bundy 79% C+ 73 75 79 80 88
Ken Larson 77% C+ 70 73 79 80 85
Wil Wheaton 75% C 70 71 75 77 80
Sarah Cortez 75% C 61 70 72 80 90
Harry Potter 73% C 69 73 73 75 77
Stannis Mannis 72% C- 60 70 75 77 78
Jon Snow 70% C- 70 70 70 70 72
John Smith 70% C- 50 60 70 80 90
Tony Hawk 65% D 60 60 60 72 72
Bubba Bo Bob 50% F 30 50 53 55 60
Hodor Hodor 48% F 33 40 50 53 62
Edwin Van Clef 47% F 33 40 50 55 57
This is my first submission on DailyProgrammer. I made my solution in Java. However, as I am new to Java programming, all feedback is very welcomed.
My solution consists of two classes, CS101Class and Student. The first one is responsible for parsing an input file, managing a list of students and determining their grades. The Student class is simply responsible for storing/printing the information of a single student.
Assuming that class roster will be given in text file roster.txt in the same directory.
Assuming that class roster will be given in text file roster.txt in the same directory.
class Student:
def __init__(self, first, last, g1, g2, g3, g4, g5):
self.first = first
self.last = last
self.grades = sorted([int(g1),int(g2),int(g3),int(g4),int(g5)])
self.avg = self.average(self.grades)
def average(self, list_of_grades):
total = 0
for grade in list_of_grades:
total += int(grade)
return total/len(list_of_grades)
def __repr__(self):
out = self.first + " " + self.last + " "
out += "("+ str(self.avg)+"%) " + "("+ determine_letter_grade(self.avg) + ")" + " "
for grade in self.grades:
out += str(grade) + " "
return out
def student_from_roster(given_line):
data = given_line.split() # puts info into list form
return Student (data[0].strip(','), data[1], data[2], data[3], data[4], data[5], data[6])
def read_roster(filename):
f = open(filename, 'r') #no need to be able to write file.
all_student_data = {}
for line in f:
all_student_data[student_from_roster(line)] = student_from_roster(line).average(student_from_roster(line).grades)
f.close()
return all_student_data
def sort_roster(roster):
return list(reversed(sorted(roster, key=lambda student:student.avg)))
def output_roster(roster_list):
"""
Accepts list of student data with each line looking like
Andrew MacDougall 100 99 98 11 22
and outputs a line like
Andrew MacDougall (66%) (B+) 11 22 98 99 100
Returns all lines in a string.
"""
out = ""
for student in roster_list:
out += student.__repr__() + "\n"
return out
def determine_letter_grade(numeric_grade):
"""
Determines letter grade based on numeric grade.
Returns letter grade.
"""
rounded_numeric_grade = int(round(numeric_grade))
if rounded_numeric_grade <= 59:
letter_grade = 'F'
elif rounded_numeric_grade >= 90:
letter_grade = 'A'
elif rounded_numeric_grade >= 80 and rounded_numeric_grade <= 89:
letter_grade = 'B'
elif rounded_numeric_grade >= 70 and rounded_numeric_grade <= 79:
letter_grade = 'C'
else:
letter_grade = 'D'
if letter_grade != 'F':
last_digit = rounded_numeric_grade % 10
if(last_digit <= 2):
if (last_digit != 0 or letter_grade != 'A'):
letter_grade += '-'
if(last_digit >=7 and letter_grade != 'A'):
letter_grade += '+'
return letter_grade
if __name__ == "__main__":
text_file = "roster.txt"
print output_roster(sort_roster(read_roster(text_file)))
C++, im a beginner so im sorry if my code stinks. Im just trying to practice here :)
#include<iostream>
#include<string.h>
#include<ctype.h>
#include<math.h>
#include<stdio.h>
class student
{
char firstname[20];
char lastname[20];
int mark1;
int mark2;
int mark3;
int mark4;
int mark5;
int percentage;
public:
void input();
void output();
void percentcalc();
int percentreturn()
{
return percentage;
};
}s[30];
void student::input()
{
std::cout<<"Enter the students first name";
std::cin>>firstname;
std::cout<<"Enter the students second name";
std::cin>>lastname;
std::cout<<"Enter the five marks in order";
std::cin>>mark1>>mark2>>mark3>>mark4>>mark5;
percentcalc();
};
void student::percentcalc()
{
int a=mark1+mark2+mark3+mark4+mark5;
int b=a/5;
percentage=b;
};
void student::output()
{
puts(lastname);
std::cout<<",";
puts(firstname);
std::cout<<"("<<percentage<<"%"<<")";
std::cout<<" ";
std::cout<<mark1<<" ";
std::cout<<mark2<<" ";
std::cout<<mark3<<" ";
std::cout<<mark4<<" ";
std::cout<<mark5<<" ";
std::cout<<std::endl;
};
void sorter(student s[],int n)
{
student temp;
for(int i=0;i<n;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(s[j].percentreturn()<s[j+1].percentreturn())
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}
}
}
int main()
{
std::cout<<"welcome to the program";
std::cout<<std::endl;
int i;
std::cout<<"Enter the number of students you want to calculate";
int n;
std::cin>>n;
for(i=0;i<n;i++)
{
s[i].input();
}
sorter(s,n);
for(int j=0;j<n;j++)
{
s[j].output();
}
}
Some people don't like using this but you could enter
include namespace std;
and avoid having to call std:: every time you use cout and cin. Generally this is bad practice in long term projects where libraries could change but short little programs like this have no issue.
Solution in Python 2.7. Experience is about 30h spent on Python, ~160h overall; mostly C(++). Moved on from Easy #168 after revising my solution there. Feedback will be much appreciated.
Code:
import re
def read_students(filename):
letter_grades = {}
for i in range(1, 60):
letter_grades[i] = 'F'
for i in range(60, 63):
letter_grades[i] = 'D-'
for i in range(63, 67):
letter_grades[i] = 'D'
for i in range(67, 70):
letter_grades[i] = 'D+'
for i in range(70, 73):
letter_grades[i] = 'C-'
for i in range(73, 77):
letter_grades[i] = 'C'
for i in range(77, 80):
letter_grades[i] = 'C+'
for i in range(80, 83):
letter_grades[i] = 'B-'
for i in range(83, 87):
letter_grades[i] = 'B'
for i in range(87, 90):
letter_grades[i] = 'B+'
for i in range(90, 93):
letter_grades[i] = 'A-'
for i in range(93, 101):
letter_grades[i] = 'A'
students = []
first_length = 0
last_length = 0
with open(filename, 'rU') as file:
entries = re.findall(r'(\w+)\s+,\s+(\w+)\s+(\d+)\s+(\d+)\s+(\d+)\s+'
'(\d+)\s+(\d+)', file.read())
for entry in entries:
if len(entry[0]) > first_length:
first_length = len(entry[0])
if len(entry[1]) > last_length:
last_length = len(entry[1])
student = [entry[0], entry[1]]
grade = 0
for i in range(2, 7):
grade += int(entry[i])
grade /= 5
student.append(grade)
student.append(letter_grades[grade])
student.extend(sorted(entry[2:7]))
students.append(student)
students = sorted(students, key=lambda student: student[2],
reverse=True)
return students, last_length, first_length
def main():
students, last_length, first_length = read_students(
'167_intermediate_data.txt')
for student in students:
print '{1}, {0} ({2}%) ({3}): {4} {5} {6} {7} {8}'.format(
student[0].ljust(first_length), student[1].ljust(last_length),
student[2], student[3].ljust(2), student[4].rjust(3),
student[5].rjust(3), student[6].rjust(3), student[7].rjust(3),
student[8].rjust(3))
if __name__ == '__main__':
main()
Solution in Python 2.7. Kept it very simple without functions or classes:
#!/usr/bin/python
#http://redd.it/28gq9b
from __future__ import print_function
import re
import sys
student_data = []
data = open("./student_data.txt", "rt").readlines()
data = [list(re.findall(r"([A-Za-z\s]+),([A-Za-z\s]+)\s+([\d\s]+)", i)[0]) for i in data]
for i in data:
dicx = {}
dicx['firstname'] = i[0].strip()
dicx['lastname'] = i[1].strip()
results = i[2].strip().split()
dicx['results'] = sorted(results)
average = 0
for i in dicx['results']:
average += int(i)
average = round(average/float(5))
average = int(average)
dicx['average'] = average
if average >= 90:
grade = "A"
elif average >= 80:
grade = "B"
elif average >= 70:
grade = "C"
elif average >= 60:
grade = "D"
else:
grade = "F"
if average % 10 > 7:
if grade in ("A", "F"):
pass
else:
grade += "+"
elif average % 10 < 3:
if grade == "F":
pass
else:
grade += "-"
dicx['grade'] = grade
student_data.append(dicx)
student_data = sorted(student_data, key=lambda k:k['average'], reverse=True)
for i in student_data:
print(i['firstname'].ljust(16), end="")
print(i['lastname'].ljust(16), end="")
print(str(i['average']).ljust(8), end="")
print(i['grade'].ljust(8), end="")
for j in i['results']:
print( str(j).ljust(8), end="" )
print("")
Here's the output:
Tyrion Lannister 95 A 100 91 93 95 97
Kirstin Hill 94 A 100 90 92 94 95
Jaina Proudmoore 94 A 100 90 92 94 95
Katelyn Weekes 93 A 90 92 93 95 97
Arya Stark 91 A- 90 90 91 92 93
Opie Griffith 90 A- 90 90 90 90 90
Clark Kent 90 A- 88 89 90 91 92
Richie Rich 88 B+ 86 87 88 90 91
Steve Wozniak 87 B 85 86 87 88 89
Casper Ghost 86 B 80 85 87 89 90
Derek Zoolander 85 B 80 81 85 88 90
Jennifer Adams 84 B 100 70 79 85 86
Matt Brown 83 B 72 79 82 88 92
Bob Martinez 83 B 72 79 82 88 92
Jean Luc Picard 82 B- 65 70 89 90 95
William Fence 81 B- 70 79 83 86 88
Alfred Butler 80 B- 100 60 70 80 90
Valerie Vetter 80 B- 78 79 80 81 83
Ned Bundy 79 C+ 73 75 79 80 88
Ken Larson 77 C 70 73 79 80 85
Sarah Cortez 75 C 61 70 72 80 90
Wil Wheaton 75 C 70 71 75 77 80
Harry Potter 73 C 69 73 73 75 77
Stannis Mannis 72 C- 60 70 75 77 78
John Smith 70 C- 50 60 70 80 90
Jon Snow 70 C- 70 70 70 70 72
Tony Hawk 65 D 60 60 60 72 72
Bubba Bo Bob 50 F 30 50 53 55 60
Hodor Hodor 48 F 33 40 50 53 62
Edwin Van Clef 47 F 33 40 50 55 57
import math
from operator import itemgetter
grades = {'A':range(90,101),
'B':range(80,90),
'C':range(70,80),
'D':range(60,70),
'F':range(0,60)}
def get_percentage(student):
return round(sum_grades(student)/500)
def percent(percentage,n):
return percentage/100*n
def sum_grades(student):
student = student.split()
return sum([int(x) for x in student[2:]])*100
def get_grade(student):
grade_list = [x for x in grades.keys()]
student_mark = get_percentage(student)
for grade in grade_list:
if student_mark in grades[grade]:
if grade == 'A' or grade == 'F':
return grade
if student_mark > max(grades[grade]) - percent(3,max(grades[grade])):
return grade +'+'
elif student_mark <= max(grades[grade]) - percent(3,min(grades[grade])):
return grade +'-'
else: return grade
def write_report(student):
report = student.split()
grades = sorted(report[2:])
for value in report[2:]:
report.remove(value)
for number in grades:
report.append(number)
report.insert(2,'('+str(get_percentage(student))+'%)')
report.insert(3,get_grade(student))
return report
def write_all():
for student in students:
write_report(student)
def sort_grades():
_all = []
for student in students:
_all.append(write_report(student))
return sorted(_all,key=itemgetter(2),reverse=True)
3
u/killedbythegrue Jun 18 '14 edited Jun 18 '14
Erlang,
I removed the spaces from the last names to make things easier on my self.
Output:
2
u/KillerCodeMonky Jun 18 '14 edited Jun 18 '14
PowerShell:
Usage:
Output:
3
u/Godspiral 3 3 Jun 18 '14 edited Jun 18 '14
in J,
g =. ;: each cutLF wd 'clippaste'
only 3 grades for zoolander
5
u/poeir Jun 18 '14 edited Jun 18 '14
Python solution with three possible outputs: HTML, Markdown, or console (using texttable). I wasn't able to figure out how to write a test for the decorator by itself, so I could use some help with that, even though the decorator is unnecessary in this case since it's only used once.
edit: In the previous version, it was specified to round up; now it specifies just round, so that's adjusted for
5
u/minikomi Jun 19 '14 edited Jun 19 '14
Racket.
Output:
7
u/skeeto -9 8 Jun 18 '14 edited Jun 18 '14
SQL, with a bit of Perl to massage the input. I'll be using SQLite's flavor of SQL to generate the report.
I created two tables with a many-to-one relationship to model the data.
students: lists all of the students without their scoresscores: lists all of the scores with a foreign key onstudentsFor simplicity, I'm assuming last names are unique so that I can use them as a primary key.
I also create a
totalsview on a [JOIN](http://en.wikipedia.org/wiki/Join_(SQL)) between these two tables. Joins are the bread and butter of relational databases. This view will look and feel just like a normal table, and it will always be up to date. Later on this will make queries involving averages much simpler because we can join with this view.I also create a table
gradesfor letter grades. I can join with this table in my report to get a letter grade column.Before I can make any use of the data, it must be converted into SQL INSERT statements. This Perl script will do that.
The output looks like this,
The tables are in place so now I can generate a report. This involves joining all of the tables above. A natural join means that when the column names match (
lastin this case) we can join wherever they hold equivalent values. To get a letter grade, I also join on thegradestable using<=and>operators to join on the correct grade letter.The output:
Unfortunately I'm still too much of a SQL newb to figure out how to list all of the scores in order in additional columns. There's probably some trick involving five left outer joins or something. I'm still working on that part.
This may seem a little bulky for such a small report, but it would scale up enormously well. After adding a few indexes in the right places, you could do all sorts of concurrent, fast queries in involving millions of students with thousands of scores each while safely making updates to the database at the same time.
1
u/poeir Jun 18 '14
I think there's an error in the problem description; it currently reads
However, the lower 3 percent of B would be [80, 81, 82], so 83% should be a B. That or it should be the lower 4 percent and either the lower 3 percent or lower 4 percent.
1
u/FTFYcent Jun 18 '14
Wait, do we need to handle malformed input ("Derek Zoolander" only has 3 grades) or is that a typo?
1
u/KillerCodeMonky Jun 18 '14
There is an error in the problem description:
The second example is not rounding up.
1
u/spfy Jun 18 '14
I cheated a little bit. The text file in the challenge was really frustrating, so I fixed it to suit my needs better. Like so:
It was pretty easy to get that text file into another Mongo database. My program that did that calculated the grade (rounding, etc). I won't include that, though.
Python 3 with MongoDB:
First few lines of output:
3
u/FerdErik Jun 18 '14 edited Jun 18 '14
Java 8 with lots of Streams, Lambdas, and RegEx.
Edit: Quickfix for names with spaces in them...
Output:
2
u/thestoicattack Jun 18 '14 edited Jun 18 '14
bash:
2
u/viciu88 Jun 18 '14 edited Jun 18 '14
My impementation in Java:
Input using regular expressions, Output using String formatting.
2
u/dreucifer Jun 18 '14 edited Jun 18 '14
Nice little python solution, nothing too fancy. Turned out quite readable. Edit: Whoops, forgot + and - grades. Edit2: Fixed.
and the output
2
u/salonabolic Jun 18 '14
C++. Didn't deal with double barreled last names - just removed the spaces!
2
u/lelarentaka Jun 18 '14 edited Jun 19 '14
Haven't seen Scala yet so I thought I'd give it a try. I'm not very good with pattern matching yet, so the letter grade part might by more verbose than it needed to be. I'm also still a beginner in regex.
Sample result. I got the formatting to be really nice by padding the names.
2
u/jnazario 2 0 Jun 20 '14
F#. did a tweak to the input to make it easier to split and parse using a regex. my exception handling leaves something to be desired.
output
2
u/darrellplank Jun 21 '14 edited Jun 21 '14
C#
Had me confused when the word "percentile" was used. In statistics, this means how many people you did better than so if you're in the 90'th percentile, you did better than 90% of the rest of the population. Here, percentile isn't really what is used but just a percentage of total grade.
1
u/Elite6809 1 1 Jun 18 '14 edited Jun 18 '14
The last record in the challenge input only has 3 grades; I'm going to assume this is a mistake and add 2 other results. Also, in the name inputs
Edwin Van ClefandJean Luc Picardhow should the program differentiate between the surnames and last names? I'll resolve that ambiguity by putting underscores in the names to join them for the input because otherwise it could be either.Anyway, here it is, in good old Ruby and some minor map-reduce abuse. It will right-align them all correctly using spaces.
Output: http://pastie.org/private/y4qrjlnngq6kupszwryd2w
1
u/Reverse_Skydiver 1 0 Jun 18 '14
My solution in Java. Deleted my previous comment as I changed the code to include + and - in the grades.
Output:
http://i.imgur.com/iaREi5V.png
1
u/Dutsj Jun 18 '14
Java 8. The style in which the entries were formatted was tougher than I thought, same with printing the output in a nicely formatted way.
Output:
1
u/kakaroto_BR Jun 18 '14
Solution in Java:
1
u/rcxdude Jun 18 '14 edited Jun 18 '14
Rust (rustc 0.11.0-pre (e55f64f 2014-06-09 01:11:58 -0700)):
Example output:
1
u/BryghtShadow Jun 18 '14
Python 3.4 and 2.7
The sample output is inconsistent, as caught by my testcase. Surely this is a typo?
Input:
Output:
1
u/dancole42 Jun 19 '14 edited Jun 19 '14
Python 2.7.6
I'm self-taught and new, so feedback is extremely appreciated.
ETA sample output and fixed the +/- cutoffs.
Output
1
u/fvandepitte 0 0 Jun 19 '14
C# later today i'll try to submit an C++ version
1
u/uprightHippie Jun 19 '14
Here is my submission in C#. This is the first time I'd ever used params, I was looking for a Regex that would collect any number of grades instead of just 5, so any comments there would be most appreciated.
Here is the main program:
Here is the Student Class:
Here is the output:
Thanks!
1
u/JMan_Z Jun 19 '14 edited Jun 19 '14
1
u/demon_ix 1 0 Jun 19 '14
Java 8. My student parsing is pretty horrible. Edit - Just noticed that because of my sort comparator, Casper the ghost appeared before Woz. Gah.
Outputs:
1
u/_M1nistry Jun 19 '14
C#. Didn't read the Output section properly/didn't plan. So it doesn't order by best-> worst. Not the nicest code but... it's 3am and /bothered. Requires a text file with the input in it at the directory named 'Students.txt'
1
u/[deleted] Jun 19 '14 edited Jun 19 '14
I know I'm probably annoying the shit out of you guys every time I post, but I am new to programming. Started with Java last September. I've been learning python over the past month. Please, please, PLEASE! point out any mistakes or bad practices in my code.
Python 2.7.7:
Inputted text file:
Output:
P.S. Those two name people like Bo Bob and van Clef really screwed me up! Hahaha.
1
u/99AFCC Jun 19 '14
Dangerous Python 2
Output:
1
u/MrP_123 Jun 19 '14
My answer in Java. Feedback is always welcome. I have to be honest, I partly used the methode of using a pattern to generate my students from another reply.
1
u/[deleted] Jun 19 '14
Late to the party. Python 2.7*
Here is the output:
1
u/gregbair Jun 19 '14
C#:
First, load the file into a string array and build a pattern for parsing the lines:
Iterate through the lines and build a Student object to hold all the info:
Then iterate through, outputting the different values:
The Student class has methods for determining the percentage and letter grade (expanded for clarity):
setFinalPercentage:
setLetterGrade (I'm sure there's an more elegant/easier way to do this):
GradesInOrder:
1
u/harrychin2 Jun 19 '14 edited Jun 20 '14
My C++ solution
I decided to call all of the relevant Student class methods in the constructor.
1
u/OnceAndForever Jun 20 '14
Lua 5.2
Usage:
Output:
I feel like there should be a more concise way of solving this using metatables and closures, but I don't really see how. Any tips would be appreciated!
1
u/joeyGibson Jun 20 '14
Here's my solution in Clojure. There is absolutely no error handling, so a proper input file is assumed.
Edit: To see a colorized version, view it at Github. It's much prettier in color.
And here's the output
1
u/Mezput Jun 20 '14
This is my first submission on DailyProgrammer. I made my solution in Java. However, as I am new to Java programming, all feedback is very welcomed.
My solution consists of two classes, CS101Class and Student. The first one is responsible for parsing an input file, managing a list of students and determining their grades. The Student class is simply responsible for storing/printing the information of a single student.
Solution
1
u/grendus Jun 20 '14 edited Jun 20 '14
Python 3.4.1. List comprehensions and lambda functions make manipulating data sets like this a breeze.
Sample output:
1
u/-AMD- Jun 21 '14
Python solution:
Assuming that class roster will be given in text file roster.txt in the same directory.
Assuming that class roster will be given in text file roster.txt in the same directory.
1
u/CodeMonkey01 Jun 21 '14
In Java:
Output:
1
u/amu05 Jun 21 '14 edited Jun 21 '14
C++, im a beginner so im sorry if my code stinks. Im just trying to practice here :)
1
u/flugamababoo Jun 21 '14 edited Jun 21 '14
Python 3.4:
output:
1
u/brugaltheelder Jun 21 '14 edited Jun 21 '14
Python. I replace the two name first and lasts with underscored names to make it easier on me. I'm trying to work on being more pythonic.
Output:
1
u/defregga Jun 24 '14
Solution in Python 2.7. Experience is about 30h spent on Python, ~160h overall; mostly C(++). Moved on from Easy #168 after revising my solution there. Feedback will be much appreciated.
Code:
Output:
1
u/[deleted] Jun 25 '14 edited Jun 25 '14
Solution in Python 2.7. Kept it very simple without functions or classes:
Here's the output:
1
u/mdlcm Jun 25 '14
I used R for this challenge.
Code:
Output
1
u/jeaton Jun 25 '14 edited Jun 25 '14
JavaScript:
Output -> http://i.imgur.com/n5lxDYI.png
1
u/kuzux 0 0 Jun 26 '14
Haskell:
1
u/eviIemons Jun 27 '14 edited Jun 27 '14
ruby
takes one file as argument and prints it (formatted) to the console
1
u/VerifiedMyEmail Jun 28 '14
Works as expected. Python 3.3
1
u/nalexander50 Jul 01 '14
Here is my solution in Python 3.3. It is not very format dependent, either! Any feedback is welcome as always.
Here is the Output.txt: http://pastebin.com/xZ4WPa6n
1
u/dp_account Jul 04 '14
Python3.4
Challenge Output:
1
u/im_not_afraid Jul 13 '14 edited Jul 13 '14
Haskell with Control.Error, Text.Printf and Text.Parsec
Output:
1
u/p44v9n Aug 01 '14
My scala solution. I added an entry to ensure percentages all lined up (presuming no one gets 100% but some may get <10%).
Comments and crits and suggestions welcome!
Lots of slicing and splitting and things that make me feel like I should learn regex.
After finishing this I read a stackoverflow answer which made me realise scala has lexicographic ordering so you can just do this at the end
1
u/[deleted] Aug 03 '14
Python 3.4
Output:
As you can see.
1
u/tally_in_da_houise Aug 13 '14
Late to the game Python 2.7 implementation:
Code: