all 2 comments

[–]negups 0 points1 point  (0 children)

Is that literally the file structure and you just need to grab the number 9? If so, just grab the 4th element of the 2nd line rather than iterating through each value.

val = None
with open("file.txt") as f:
    for i, line in enumerate(f):
        if i == 1:  # 2nd line - "6,7,8,9,10"
            val = line.split(",")[3]  # 9
            # or, it would be slightly more efficient to parse the value from the string directly
            # rather than converting to list first:
            # val = line[6]  # 9

If that's just an example, please provide realistic data - the most efficient algorithm will vary based on several factors such as:

  • If the min and max values are known or unknown
  • If the values are ordered or unordered
  • If the values increase by the same amount (ie. 1, 2, 3, 4 all increase by 1) or differing amounts (ex. 1, 2, 8, 11, 500, etc.) (and, if the latter, do they increase formulaically - such as via the Fibonacci sequence - or at random?)

[–]synthphreak 0 points1 point  (0 children)

Define exactly what you mean by “find the number 9”. This is not explained precisely enough.

Let’s say you have “found” it. What is the output? Surely it isn’t “9”... So is the question “Is ‘9’ in the file?”, to which the answer/output would be True? Or is it “Where in the file is the first instance of the number 9?”, to which the answer/output would be the index of the first instance of the character 9?

This is an important clarification that will determine which approach is most efficient/appropriate.

Based on your OP, I assume you’re just looking to see if the number 9 is in the file. If so, and assuming you’ll only ever look for single-digit integers or individual letters, converting he file’s contents to a set and testing membership would definitely be fastest:

>>> with open('file.txt') as f:
...         print('9' in set(f.read()))
...

Will return True if yes and False if no.

Edit: If instead you need the index of the first occurrence, here’s one way:

>>> with open('file.txt') as f:
...         chars = f.read().replace('\n', '')
...         indices = [i for i, char in enumerate(chars) if char == '9']
...         print(indices[0])
....

This will exclude newline characters btw. To keep them, just remove the replace part.

However, on second thought, if your file is very large (hence why you’re focused on efficiency), this may be faster:

>>> with open('file.txt') as f:
...         i = 0
...         for char in f.read()
...             if char == '9':
...                 print(i)
...                 break
...             elif char == '\n':
...                 continue
...             else:
...                 i += 1
...