HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Counting which numbers fall in a certain bracket

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
countingnumberscertainbracketwhichfall

Problem

I'm taking a text file that looks like this:

77, 66, 80, 81
40,  5, 35, -1
51, 58, 62, 34
 0, -1, 21, 18
61, 69, 58, 49
81, 82, 90, 76
44, 51, 60, -1
64, 63, 60, 66
-1, 38, 41, 50
69, 80, 72, 75


and I'm counting which numbers fall in a certain bracket:

f = open("//path to file", "r")
text = f.read()
split = text.split()

greater70=0
sixtys=0
fiftys=0
fortys=0
nomarks=0

for word in split:
    temp = word.replace(',', '')
    number = int(temp)
    if number > 70:
        greater70+=1
    if number >= 60 and number = 50 and number = 40 and number <= 49:
        fortys+=1 
    if number == -1:
        nomarks+=1           

print greater70 
print sixtys
print fiftys
print fortys
print nomarks


Have I done it in an efficient way sensible way or do experienced Python users think it looks a little convoluted?

Solution

Notes:

-
Creating so many variables is a warning sign that they should be grouped somehow (an object, a dictionary, ...). I'd use a dictionary here.

-
Consider learning some functional programming (as opposed to imperative programming) to apply it when it improves the code (IMO: most of the time). Here it means basically using collections.counter and generator expressions.

-
Don't read whole files, read them line by line: for line in file_descriptor.

-
There are programmatic ways of detecting intervals of numbers (simple loop, binary search). However, since you have here only 5 intervals it's probably fine just to write a conditional as you did. If you had, let's say 20 intervals, a conditional branch would be a very sad thing to see.

-
Conditional branches are more clear when you use non-overlapping conditions with if/elif/else (effectively working as expressions instead of statements).

I'd write:

from collections import Counter

def get_interval(x):
    if x > 70:
        return "greater70"
    elif 60 = 50:
        return "fiftys"
    elif x >= 40:
        return "fortys" 
    elif x == -1:
        return "nomarks"   

with open("inputfile.txt") as file:
    counter = Counter(get_interval(int(n)) for line in file for n in line.split(","))
# Counter({'sixtys': 10, 'greater70': 10, None: 7, ..., 'fortys': 4})

Code Snippets

from collections import Counter

def get_interval(x):
    if x > 70:
        return "greater70"
    elif 60 <= x < 70:
        return "sixtys"    
    elif x >= 50:
        return "fiftys"
    elif x >= 40:
        return "fortys" 
    elif x == -1:
        return "nomarks"   

with open("inputfile.txt") as file:
    counter = Counter(get_interval(int(n)) for line in file for n in line.split(","))
# Counter({'sixtys': 10, 'greater70': 10, None: 7, ..., 'fortys': 4})

Context

StackExchange Code Review Q#26958, answer score: 4

Revisions (0)

No revisions yet.