I need to do this:
"""
Program a function
def increasing (m)
that will be able, for any matrix m of positive integers, to check whether the sums of the rows in this array are increasing.
examples
1 3 2 5 The sums of the rows 2 8 4 1 The sums of the rows
7 9 4 1 are 11, 21 and 23. 6 2 8 5 are 15, 21 and 15.
3 5 6 9 --> increasing 8 4 2 1 --> not increasing
"""
So, I want to use sum(), which is perfectly doable, I guess.
I started like this:
def increasing (m):
for row in m:
row[1]
But I know that row[1] will just output the numbers in index 1 of each row. What I have in my mind is this:
def increasing (m):
for row in m:
if sum(row)[first_row] > sum(row)[second_row]:
return False
But that is just slicing it, so I don't know how to count the rows so that I can compare them.
I don't want to use any module or whatsoever, just plain simple Python. Can someone point me in the right direction? I just need it to be as simple as possible.
Input format sample:
increasing_l = [
[1, 3, 2, 5],
[7, 9, 4, 1],
[3, 5, 6, 9]
]
not_increasing_l = [
[2, 8, 4, 1],
[6, 2, 8, 5],
[8, 4, 2, 1]
]
test1 = increasing(increasing_l)
test2 = increasing(not_increasing_l)
print "should be True: %s" % test1
print "should be False: %s" % test2
You can do the following:
def increasing(m):
return all(sum(r1) < sum(r2) for r1, r2 in zip(m, m[1:]))
This uses zip to pair adjacent rows and all to efficiently do the pairwise sum comparison.
Without zip:
return all(sum(m[i-1]) < sum(m[i]) for i in range(1, len(m)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With