Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Counts of integers seen in file aren't being updated

I made a little script that is supposed to iterate over a text file and read the numbers.
Once a number is read, another variable which measures the frequency of each number is supposed to get updated so that the frequency of the number increases by 1.

I’ve tested every part of this program on its own and they work, however the problems start when I put it all together.

My code is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import sys

f = open("PythonRandomNums", "r")
ZeroCount = 0
...
NineCount = 0

for x in range(text_file_lines):
current_num = f.readline(x)
if current_num == 0:
ZeroCount += 1
...
elif current_num == 9:
NineCount += 1

obs_freq = [ZeroCount, ... NineCount]
print(f"Observed Frequencies: {obs_freq}")

And the output is

Observed Frequencies: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

>Solution :

readline returns a string. Even if this string only contains digits, it is not equal to a number like 0. And the string actually also contains a newline character.

You need to convert the string to an integer. This will raise an exception if the line does not contain just an integer (plus optional surrounding whitespace).

current_num = int(f.readline())

By the way, iterating over range(text_file_lines) to read from a file is strange. Normally you would iterate directly over the file object, which gives a stream of lines:

for line in f:
    current_num = int(line)
    …

Next, rather than use separate variables for each number, why not use a single dictionary?

count = {}
for line in f:
    current_num = int(line)
    count[current_num] = count.get(current_num, 0) + 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading