Home > Software design >  How to count the amount of 1s in one of the rows in a matrix?
How to count the amount of 1s in one of the rows in a matrix?

Time:05-22

I am currently trying to input a matrix and have the python code be able to go row by row to count how many 1s there are in that row. Then I would have all the data be outputted in a row. But right now, I am kind of stumped on how to collect the data and output it in a row.

Note, this is my input method example:

2 3
1 1 3
1 2 0
1 2 3

output I get:

1
1
1

output I tried to get:

2
1
1

Here is the code that I need help fixing:

n, m = map(int, input().split())
#input
for i in range(n):
  l = list(int(m) for m in input().split())
#repeating rows of list inputs for matrix
  
if len(l) < m or len(l) > m:

  
    print("no")
    #if statement for checking length of lists
else:
    for b in range(n):
    #the count function, and unfortunately the part that is wrong                 
        v = l.count(1)
        print(v)

I pretty much want to know how to output all the data in a row.

CodePudding user response:

Your code has a few issues. For one, it would be good to tell a (human) user what they need to enter - an automated user won't care about it either way:

print('Enter the number of rows and the length of each row, separated by a space:')
n, m = map(int, input().split())

(or you can do that in the input() call)

Although your question is really about the final bit of the code, your input code also has an error: you replace the entire list with the input for every iteration, so you only end up with the final row in l.

A better way to write the whole input bit:

n, m = map(int, input('Number of rows and length of each row, separated by spaces: ').split())
l = []
for i in range(n):
    row = list(map(int, input(f'{m} values, for row {i}, separated by spaces: ').split()))
    if len(row) != m:
        print('Each row must have {m} values!')
        exit()
    l.append(row)

But for purposes of your question, you could just write something like:

# 2 rows of 3 values
l = [[1, 2, 3], [1, 1, 1]]

(it makes sense to have some different numbers of 1's on each line?)

Now that the values are actually lists in a list, you can just loop over the lists and do what you were doing:

for xs in l:
    v = xs.count(1)
    print(v)

The key thing was first appending each row the list of lists you were constructing (after all, you're after 2d matrix) and then to loop over each row, and count the elements of each row separately. You can just use for as shown to loop over each element of an iterable, like a list.

The result:

l = [[1, 2, 3], [1, 2, 3]]
for xs in l:
    v = xs.count(1)
    print(v)

The output:

1
1
  • Related