I feel like my code is correct, but keep getting wrong output for this homework question.
The problem is:
Below are a set of scores that students have received in the past semester. Write code to determine how many are 90 or above and assign that result to the value a_scores.
scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100"
#my attempt below
accum = 0
for sc in scores:
if sc >= 90:
accum = accum + 1
a_scores = accum
print(a_scores)
Output:
85
#should be 10
#looking at it again, it appears to be just counting the number of characters (incl. spaces) that are in the string scores, (i.e., 85 characters)
I got:
Error:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: unorderable types: str() >= int()
Do something like this prior your loop:
scores = map(int, scores.split())
or
a_score = len(list(filter(lambda x: x >= 90, scores)))
Another possibility:
>>> scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100"
>>> sum(1 for x in scores.split() if 90 <= int(x))
10
Of course there is also
Counter in collections module:
Quote:A Counter is a dict subclass for counting hashable objects.
(May-06-2019, 05:39 AM)scidam Wrote: [ -> ]I got:
Error:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: unorderable types: str() >= int()
That's the difference between Python-2
* and Python-3 when unequal types are compared.
(*
tried to read up on this for Py2 ... but gave up on that idea very very quickly*)
*)
or when Trinket(default free version) is used without #!/bin/python3
as first line. Right, even with #!/bin/python3
Trinket happily processed that str() >= int()
part.
(back to the drawing board ... right, effects only syntax evaluation)))
An answer to problem:
scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100"
scoressplit = scores.split()
#print(scoressplit)
accum = 0
for sc in scoressplit:
if int(sc) >= 90:
accum = accum + 1
a_scores = accum
print(a_scores)
Output:
10
Some observations and suggestions.
- there is no reason to assign names to objects like
scoressplit
and
accum
if you don't need them
- use descriptive names i.e.
sc
->
score
- use
+=
- use comparison operators in ascending flow i.e 90 <= int(score), it makes easier for human to mentally parse comparison
scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100"
a_scores = 0
for score in scores.split():
if 90 <= int(score):
a_scores += 1
print(a_scores)