Home > Blockchain >  How can I change this function so that it returns a list of the number of even digits in a file?
How can I change this function so that it returns a list of the number of even digits in a file?

Time:10-27

def evens(number_file: TextIO) -> List[int]:
    lst = []
    
    line = number_file.readline().strip()
    while line != '':
        evens = 0
        line = number_file.readline().strip()
        
        while line.isdigit():
            evens = evens   int(line)
            line = number_file.readline().strip()
        lst.append(evens)
        
    return last

in this example the file 'numbers.txt' looks like this:

START

1

2

END

START

3

END

START

4

5

6

END

Each line is either an int or 'START' or 'END' I want to make a function that returns the number of evens in each section so when the code tuns on this file, it should return the list [1, 0, 2]. Could someone please help me?

CodePudding user response:

import numpy as np

def main():
    line = [1,4,5,6,8,8,9,10]
    evens = np.array()
    for l in line:
        if (l % 2) == 0:
            np.append(evens, l)
    return evens

if __name__ == '__main__':
    main()

Without your txt file and the code to read it in, this is the best I can do.

CodePudding user response:

When writing new code, it's a good idea to start small and then add capabilities bit by bit. e.g., write code that works without worrying about sections first, then update to work with sections.

But anyway, here's some revised code that should work:

def evens(number_file: TextIO) -> List[int]:
    lst = []
    
    line = number_file.readline().strip()
    while line != '':
        evens = 0

        # ignore all text lines
        while !line.isdigit():
            line = number_file.readline().strip()

        # process number lines
        while line.isdigit():
            if int(line) % 2 == 0:
                evens = evens   1
            line = number_file.readline().strip()

        lst.append(evens)
        
    return lst

And here's a version that may be simpler (for loops in Python can often make your life easier, e.g. when processing every row of a file):

def evens(number_file: TextIO) -> List[int]:
    lst = []

    for row in number_file:
        line = row.strip()
        if line == 'START':
            # new section, start new count
            lst.append(0)
        elif line.isdigit() and int(line) % 2 == 0:
            # update current count (last item in lst)
            lst[-1]  = 1

   return lst
  • Related