Search code examples
pythonnumpymatrixlimit

Python - Limiting number of rows (numpy)


I almost finished my code. Need a little help from you.

import numpy as np
A = list()
n = int(input("How many rows: "))
m = int(input("How many columns: "))

for x in range(n):
    if n <= 0 or n>10:
         print("Out of range")
         break
    elif m <= 0 or m>10:
         print("Out of range")
         break
    else:
        for y in range(m):
             num = input("Element: ")
             A.append(int(num))

shape = np.reshape(A,(n,m))

a = np.array(shape)
for row in a:
    neg_sum = sum(row[row < 0])  # sum of negative values
    print('{} Sum of Negative Elements In This Row: {}'.format(row, neg_sum))

I needed to get matrix and i have it, user enters number of columns and rows and coming out of this also enters needed amount of elements, also i wanted to get sum of all negative numbers in every row, here is the output.

How many rows: 3
How many columns: 3
Element: -1
Element: 2
Element: -3
Element: 4
Element: 5
Element: -6
Element: -7
Element: -8
Element: 9
[-1  2 -3] Sum of Negative Elements In This Row: -4
[ 4  5 -6] Sum of Negative Elements In This Row: -6
[-7 -8  9] Sum of Negative Elements In This Row: -15
Press any key to continue . . .

But i have one problem, i need to get sum of all negative numbers in each row, till the 7th. Right now if i make 8x8 9x9 or whatever that is bigger than 7, still it counts all the matrix, if i use [:7,:] it ends matrix on 7th and cuts down everything else, even if matrix is 8x8.

So i need to somehow limit "SUM" without limiting "Matrix"

Need to get whole matrix and sum of all negative numbers in each row till the 7th.

Giving you an example, if i have matrix (2x8) :

[-1,-1,-1,-1,-1,-1,-1,-1] This gives answer -8
[-1,-1,-1,-1,-1,-1,-1,-1] This gives answer -8

I need to get answer :

[-1,-1,-1,-1,-1,-1,-1,-1] This should give -7
[-1,-1,-1,-1,-1,-1,-1,-1] This should give -7

Any help?


Solution

  • hi i'm not entirely sure what your looking for but does this work?

    import numpy as np
    import random
    A = list()
    n = int(input("How many rows: "))
    m = int(input("How many columns: "))
    
    for x in range(n):
        if n <= 0 or n>10:
             print("Out of range")
             break
        elif m <= 0 or m>10:
             print("Out of range")
             break
        else:
            for y in range(m):
                 #num = input("Element: ")
                 num = random.randint(-1,1)
                 A.append(int(num))
    
    shape = np.reshape(A,(n,m))
    
    a = np.array(shape)
    for row in a:
        keep_row = row
        row = row[0:7]
        neg_sum = sum(row[row < 0])  # sum of negative values
        print('{} Sum of Negative Elements In This Row: {}'.format(keep_row, neg_sum))
    

    it just splits the array from the start till the 7th and adds up that seven, your original matrix's row is safe in keep_row