Give a positive integer n not greater than 9 and output a “Snake matrix” with n rows and n columns. For example: Input: 4 output:
时间: 2024-03-26 10:34:04 浏览: 82
greater-than.js:给定值或对象属性中的值是否大于 X
Sure, I can help you with that! Here's a Python code that generates a Snake matrix with n rows and n columns for a positive integer n not greater than 9:
```
n = int(input("Enter a positive integer not greater than 9: "))
matrix = [[0] * n for i in range(n)]
num = 1
for i in range(n):
if i % 2 == 0:
for j in range(n):
matrix[i][j] = num
num += 1
else:
for j in range(n-1, -1, -1):
matrix[i][j] = num
num += 1
for row in matrix:
print(row)
```
This code first prompts the user to enter a positive integer not greater than 9, creates an empty matrix of size n x n, and then fills in the matrix in a "snake" pattern by iterating over each row and column. Finally, it prints the matrix to the console.
For example, if the user enters 4, the output will be:
```
[1, 2, 3, 4]
[8, 7, 6, 5]
[9, 10, 11, 12]
[16, 15, 14, 13]
```
I hope this helps! Let me know if you have any other questions.
阅读全文