Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

making it more efficient #168

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

MahyarFardin
Copy link

Reading file inside for loop is something costly!!!!

Reading file inside for loop is something costly!!!!
@dabeaz
Copy link
Contributor

dabeaz commented Aug 18, 2023

Deviates significantly from other course material. Would only accept if noted as some kind of comment attached to the original solution.

@dg1223
Copy link

dg1223 commented Sep 22, 2024

with open(filename) is fine. It is computationally efficient. Explained here.

When we write:

with open(filename) as f:
    for line in f:
        # use line in code

the loop looks at one line at a time. This has the advantage of requiring very little memory — only enough memory to hold the chars of a single line at a time, even though the file might have thousands or millions of lines of text in total.

The suggested fix with f = open(filename, 'rt') needs to close the file with f.close() which is not included in the PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants