python matrix creation without using numpy or anything and max sum of rows and columns
<p>Want to create a matrix like below in python</p>

<pre><code>[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
</code></pre>

<p>but not sure how to do, i tried list comprehension like below</p>

<pre><code>[[y+x for y in range(4)] for x in range(4)]
</code></pre>

<p>which gives output like below</p>

<pre><code>[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
</code></pre>

<p>and also want print the row with maximum sum and columns with maximum sum.</p>

<p>Thanks in advance </p>

<pre><code>[[x * 4 + y + 1 for y in range(4)] for x in range(4)]
</code></pre>

<p>which is equivalent to:</p>

<pre><code>[[(x &lt;&lt; 2) + y for y in range(1, 5)] for x in range(4)]
</code></pre>

<p>Here's a little benchmark:</p>

<pre><code>import timeit


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


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


def f3():
    a = range(1, 5)
    return [[(x &lt;&lt; 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]
</code></pre>

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

python matrix