Вопрос задан 04.11.2023 в 05:54. Предмет Информатика. Спрашивает Акура Накизука.

НА ПИТОНЕ, ПОМОГИТЕ ПОЖАЛУЙСТА! # -*- coding: utf-8 -*- ''' Список-массив из n целых чисел

генерируется случайным образом в диапазоне от a до b. Числа n, a, b вводятся по запросу с экрана. Выведите полученный массив на экран. Затем с экрана запрашивается произвольное целое число d (не обязательно из диапазона от a до b). Найдите в полученном массиве элемент, самый близкий по величине к данному числу d, но не равный ему. Если таких чисел несколько — выведите любое из них. Также выведите его индекс. Замечание. Вам понадобится функция для вычисления абсолютной величины числа. Она есть в Питоне, это abs(x). !!! Никаких методов Питона для работы с массивами, кроме append и len, !!! использовать нельзя. '''
0 0
Перейти к ответам

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

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

from math import *

from random import *

# Импортирую нужные библиотеки

Num = int(input("Товарищ, ввиди количество элементов в массиве"))

a = int(input("Случайные числа от: "))

b= int(input("До: "))

My_Table = []

for num in range(Num):

        My_Table.append(randint(a,b))

print(My_Table)

#Вторая часть задания с параметром D

d = int(input("Ввиди любое число и я смогу найти максимально близкое, но не равное ему число: "))

Record_abs = []

mt = My_Table

for object in range(len(My_Table)):

      Record_abs.append([abs(mt[object]-d),object])

record = Record_abs[0]

for absolutes in range(len(Record_abs)):

               if Record_abs[absolutes][0]<record[0] and Record_abs[absolutes][0]!=0:

                         record=[Record_abs[absolutes][0],absolutes]

if record[0]!=0:

      print("Ваше число: " + str(My_Table[record[1]]))

      print("Индекс числа в твоем массиве: "+str(record[1]))

     

Вроде работает)!

Обьяснение:

Алгоритм создание случаных чисел и впендюривание их в массив таков:

1.Используйте метод randint в классе random для создание случайных чисел на диапозоне

random.randint(Дипозон1, Дипозон2) =>  random.randint(4, 14) - Случайное число от 4 до 14

2.Чтобы вставить в конце массива элемент надо использовать функцию append привязонную ко всем обьктам класса list

Super_puper_krutoi_masiv = []

Super_puper_krutoi_masiv.append(11)  #Super_puper_krutoi_masiv = [11]

Во второй части задание все чуть посложнее:

Чтобы сравнивать кто ближе, надо знать растояние!

Растояние между цислами = Модуль(Число1 - Число2)

Пример:

Растояние между 7 и 5 будет 2, так, как |7-5| = 2

Растояние между 5 и 7 будет 2, так, как |5-7| = 2

abs() - функция возведения числа в модуль

Делаем тоже самое, только место случайных чисел, отнимаем число d, чтобы определить растояние до него

abs(mt[object]-d)

Также в условие говорится одна вешь - Элемент массива не должен быть равен числу, которое мы ишем( тоесть число d)

[9,9,9,10,10] , при d = 10 ==> 9

Чтобы избежать токого, надо прописать строчку в условие:

Record_abs[absolutes][0]!=0

Так,как ответ может быть таким, лишь при растоянии равным 0

Далее я пихаю всю информацию о растояниях и индексах массивов в перемменную Record_abs

переменная record = [растояние,индекс числа]

массив Record_abs[Индекс] = [растояние,индекс числа]

Ну, вот так, как то!)

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

Generating a Random Array

To generate a random array of n integers within a given range [a, b], you can use the `random` module in Python. Here's an example code snippet that accomplishes this:

```python import random

n = int(input("Enter the number of elements in the array: ")) a = int(input("Enter the lower bound of the range: ")) b = int(input("Enter the upper bound of the range: "))

array = [] for _ in range(n): array.append(random.randint(a, b))

print("Generated array:", array) ```

In this code, we first import the `random` module. Then, we prompt the user to enter the number of elements in the array (`n`), the lower bound of the range (`a`), and the upper bound of the range (`b`). We initialize an empty list called `array` and use a loop to generate `n` random integers within the range [a, b] using the `random.randint()` function. Finally, we print the generated array.

Finding the Closest Element

To find the element in the generated array that is closest in value to a given number `d`, but not equal to it, you can iterate over the array and keep track of the closest element found so far. Here's an example code snippet that demonstrates this:

```python d = int(input("Enter the number to compare: "))

closest_element = array[0] closest_difference = abs(array[0] - d)

for element in array: difference = abs(element - d) if difference < closest_difference and element != d: closest_element = element closest_difference = difference

closest_index = array.index(closest_element)

print("Closest element:", closest_element) print("Index of closest element:", closest_index) ```

In this code, we prompt the user to enter the number to compare (`d`). We initialize `closest_element` and `closest_difference` with the first element of the array and its absolute difference from `d`, respectively. Then, we iterate over each element in the array and calculate the absolute difference between the element and `d`. If the difference is smaller than the current closest difference and the element is not equal to `d`, we update `closest_element` and `closest_difference`. Finally, we find the index of the closest element using the `index()` method and print the closest element and its index.

Please note that the code provided above assumes that you have already generated the array as described in the previous section.

0 0

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

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

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

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