H. Minear
H. Minear

Reputation: 87

Finding Amount of Numbers in a certain range

I am working with a text file filled with strings of numbers that are seperated by white space. I am trying to find the amount of numbers in the file that have a value between 1 and 1,000,000. I currently have this which just prints the number. Any advice on how to find the amount of numbers?

for line in file: 
    for number in line:
        if "0" < number < "1000000":
            print(number)

Upvotes: 2

Views: 102

Answers (4)

Mason Bryant
Mason Bryant

Reputation: 1392

file_object = open("numbers", "r")
count = 0
for line in file_object:    
    for number in line.split():
        if int(number) > 10 and int(number) < 100:
            count = count + 1
print(count)

Upvotes: 0

Mohd
Mohd

Reputation: 5613

If they file has only numbers, you can use something like:

with open(path, 'r') as f:
    print sum(1 for x in f.read().split() if 10000 > int(x) > 0 )

This will count the numbers in the whole file without counting each line separately.

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

Your approach is incorrect since:

  • number is every character of a line. So these can only be digits, letters, etc. Not multi-digit numbers; and
  • comparison with strings is lexicographically.

You can however easily calculate this like:

sum(0 < int(n) < 1000000 for line in file for n in line.split() if n.strip())

The int(..) casts a string to its equivalent (integral) number. So '100' is converted to 100. This is necessary if we want to perform numerical comparisons.

The split() is used to obtain the numbers in the file. It will look for whitespace, etc. and split on these parts.

The if n.strip() can be optional if the number is well formatted. But this can be problematic: for instance if you have tailing new lines, etc.

Upvotes: 4

Cory Madden
Cory Madden

Reputation: 5193

First, cast your number variable to an int like this: int(number) and use ints instead of strings to compare. Like this: if 0 < int(number) < 10000.

Also, add a counter like some comments suggested. Here is the completed code:

counter = 0
for line in file: 
    for number in line:
        if 0 < number < 1000000:
            counter += 1

Upvotes: 1

Related Questions