[Solved] How do I write code for a specific matrix?


Here’s the Pythonic way to do it:

sz = int(input("Size? "))
print("\n".join([" ".join([str(base + delta + 1) for delta in range(sz)]) for base in range(sz)]))

Sample runs are (for inputs of 4 and 5):

Size? 4
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7

Size? 5
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9

Of course, I wouldn’t hand that in as classwork unless you can explain how it works 🙂

In terms of how it works, it uses list comprehension (nested) to form each individual row from each item, and the matrix as a whole from the rows. It also uses string.join() to turn those lists into strings with a specific separator character.

The expression:

[str(base + delta + 1) for delta in range(sz)]

is a list comprehension that gives a list of the strings created from the integers formed by the sum of base, delta and 1, where delta ranges from 0 to sz - 1 inclusive (base comes from the outer comprehension below).

That’s the inner comprehension which we than pass into " ".join(), and that joins up all the elements of the list into a single string where each element is separated by a space.

The outer comprehension:

[<joined-inner>) for base in range(sz)]

does a similar job, creating a list of joined rows, providing a different base for each row. We then pass that into "\n".join() which joins all the rows into a single string, and each row separated by a newline character.


For a more conventional (non-Pythonic) method, you can use:

sz = int(input("Size? "))
for base in range(sz):
    for delta in range(sz):
        print(base + delta + 1, end=" ")
    print()

2

solved How do I write code for a specific matrix?