Вопрос задан 17.06.2023 в 22:53. Предмет Информатика. Спрашивает Березкин Иван.

Нужно написать программу на Python (желательно чтобы входной текст работал и в компиляторе):

Заполнить квадратный массив А (NхN) элементов (N вводится с клавиатуры) числами из одномерного массива В (длиной не более 64 элементов) "змейкой" – сперва первую колонку сверху вниз, затем вторую снизу вверх и т.д. Массив В предварительно заполняется из входного текстового файла. Оба массива распечатать.
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Горлач Даша.

Ответ:

try:

 n = int(input("Please, input an N: "))

except:

 print("N - should be an integer")

if ( n > 64):

   print("N should be lower than 64")

   print("The program is closed")

   exit(0)

print("Filling array B from file...")

b = []

my_file = open("c:\B_array.txt", "r")

content = my_file.read()

b = content.split(",")

my_file.close()

print("Filling associate array A NxN from array B...")

a_row = []

a = []

for j in range(n):

 a_row = []

 for i in range(n):

   a_row.append(b[j*n+i])

 a.append(a_row)

print("Array A: "+ str(a))

print("Array B: " + str(b))

Объяснение:

Все описание в самой программе

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

Program to Fill a Square Array in Python

Here's a Python program that fills a square array `A` of size `N x N` with elements from a one-dimensional array `B` of length not exceeding 64, using a "snake" pattern. The program also prints both arrays.

```python def fill_array(N, B): A = [[0] * N for _ in range(N)] index = 0

for i in range(N): if i % 2 == 0: for j in range(N): A[j][i] = B[index] index += 1 else: for j in range(N - 1, -1, -1): A[j][i] = B[index] index += 1

return A

# Example usage N = int(input("Enter the size of the square array: ")) B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] # Replace with your own array

A = fill_array(N, B)

print("Array A:") for row in A: print(row)

print("Array B:") print(B) ```

This program defines a function `fill_array` that takes the size of the square array `N` and the one-dimensional array `B` as input. It initializes an empty square array `A` of size `N x N` with zeros. Then, it iterates over the rows of `A` and fills them with elements from `B` in a "snake" pattern. Finally, it returns the filled array `A`.

The program also includes an example usage where the size of the square array `N` is taken from user input, and the one-dimensional array `B` is provided as a predefined list. You can replace the list `B` with your own array.

Please note that the program assumes that the size of the square array `N` is a positive integer and that the length of the one-dimensional array `B` is not greater than `N^2`. You may need to add input validation or modify the program according to your specific requirements.

Let me know if you need any further assistance!

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос