2

Want to create a matrix like below in python

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

but not sure how to do, i tried list comprehension like below

[[y+x for y in range(4)] for x in range(4)]

which gives output like below

[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]

and also want print the row with maximum sum and columns with maximum sum.

Thanks in advance

1

4 Answers 4

4
[[x * 4 + y + 1 for y in range(4)] for x in range(4)]

which is equivalent to:

[[(x << 2) + y for y in range(1, 5)] for x in range(4)]

Here's a little benchmark:

import timeit


def f1():
    return [[x * 4 + y + 1 for y in range(4)] for x in range(4)]


def f2():
    return [[(x << 2) + y for y in range(1, 5)] for x in range(4)]


def f3():
    a = range(1, 5)
    return [[(x << 2) + y for y in a] for x in range(4)]

N = 5000000
print timeit.timeit('f1()', setup='from __main__ import f1', number=N)
print timeit.timeit('f2()', setup='from __main__ import f2', number=N)
print timeit.timeit('f3()', setup='from __main__ import f3', number=N)

# 13.683984791
# 13.4605276559
# 9.65608339037
# [Finished in 36.9s]

Where we can conclude both f1 & f2 methods give almost the same performance. So it'd be a good choice to calculate the inner range(1,5) only once like f3

Sign up to request clarification or add additional context in comments.

Comments

3

The range function accepts 3 arguments start, end and step. You can use one range with step 4 and another one for creating the nested lists using the outer range.

>>> [[i for i in range(i, i+4)] for i in range(1, 17, 4)]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

here is another way with one range:

>>> main_range = range(1, 5)
>>> [[i*j + (i-1)*(4-j) for j in main_range] for i in main_range]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

And here is a Numpythonic approach:

>>> n = 4
>>> np.split(np.arange(1, n*n + 1), np.arange(n ,n*n, n))
[array([1, 2, 3, 4]), array([5, 6, 7, 8]), array([ 9, 10, 11, 12]), array([13, 14, 15, 16])]

Comments

1

try this,

In [1]: [range(1,17)[n:n+4] for n in range(0, len(range(1,17)), 4)]
Out[1]: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

Comments

0

This might be a quick fix

[([x-3,x-2,x-1,x]) for x in range(1,17) if x%4 ==0]

But what do you mean by maximum sum of column and row

1 Comment

for ex. in all rows which of the row has the maximum sum, for ex. 2nd row liks this [1 2 3] has maximum sum of = some value, here its 6.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.