Newby
Newby

Reputation: 1

Counting the number of cells in a matrix using Python

I have a file that contains a matrix the first row shows the number of rows 3, columns 5.

    3 5 
    TTTTT
    TMMMT
    TTTTT

I am writing a python program to divide the columns and sum up the number of cells,

    TT
    TM
    TT

    total number = 6

the second two

    TT
    MM
    TT
    total number= 6

and the final one

    T
    T
    T

    total number = 3

The code I have so far

 rows = []
with open('example.in') as fp: #the file name is example.in
    for line in fp:
     rows.append(line.strip()) #removes white spaces 

    for i , rowi in enumerate(rows[1:]): #slices out the first row
      print(len(rowi))

the output

    5
    5
    5

It is adding up the number of cells in each row. I am new in python programming.

Upvotes: 0

Views: 1639

Answers (1)

mke21
mke21

Reputation: 165

Maybe like this?

def count_cells_row(file_in):
    """
    generator to count cells per row

    file_in -- fileobject containing matrix
    """
    for row in file_in:
        row = row.strip()
        if row:
            yield len(row)

with open('/path/to/file') as file_in:
    ncells = sum([i for i in count_cells_row(file_in)])

print (ncells)

So I first make a generator that produces the length of the rows per iteration. Then I make a list of these values by list comprehension ([i for i in count_cells_row(file_in)]), this is another way of making a loop. The results of that will be in your case [5, 5, 5].

I use the python function sum to calculate the sum of these values.

Upvotes: 1

Related Questions