Вопрос задан 16.06.2023 в 21:25. Предмет Информатика. Спрашивает Fazilov Samir.

Python. Функция randint Я делаю Д/З по информатике и столкнулся с такой проблемой, что когда я

ввожу функцию randint, указываю количество нужных мне рандомных чисел и указываю промежуток, в пределах которого должны выбраться рандомные числа, то в результате могут выпасть несколько одинаковых чисел. Подскажите, что надо сделать, чтобы рандомные числа были разными и не повторялись?​
0 0
Перейти к ответам

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

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

Ответ:

import random

check = []

count_res = 0

count = 0

for i in range(7):

   number = random.randint(2, 9)

   if number not in check:

       check.append(number)

       print(number)

       count += 1

   count_res += 1

if count != count_res:

   for j in range(count_res - count):

       for z in range(2, 10):

           if z not in check:

               print(z)

               count += 1

           if count_res - count == 0:

               quit()

Объяснение:

Предлагаю такой вариант. Единственное если изменяешь диапозон( у меня он 2, 9), то в for(у меня он 2, 10) второе число + 1. Ну как видишь( было 2, 9 => 2, 10).

Числа не повторяются, их сколько нужно, но нужно следить, чтобы колво запрашиваемых чисел( это первый for = 7 у меня) было не больше диапозона, иначе числа будут повторятся.

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

The `randint` function in Python

The `randint` function in Python is a part of the `random` module and is used to generate random integers within a specified range. It takes two arguments: the lower bound and the upper bound of the range. For example, `random.randint(1, 10)` will generate a random integer between 1 and 10 (inclusive).

Generating unique random numbers

If you want to generate a sequence of unique random numbers, you can use the `sample` function from the `random` module instead of `randint`. The `sample` function returns a specified number of unique elements chosen randomly from a sequence.

Here's an example of how you can use the `sample` function to generate a sequence of unique random numbers within a given range:

```python import random

lower_bound = 1 upper_bound = 10 num_numbers = 5

random_numbers = random.sample(range(lower_bound, upper_bound + 1), num_numbers) print(random_numbers) ```

In this example, `random.sample(range(lower_bound, upper_bound + 1), num_numbers)` generates a list of `num_numbers` unique random numbers between `lower_bound` and `upper_bound`. The `range` function is used to create a sequence of numbers within the specified range.

By using the `sample` function, you ensure that the generated random numbers are unique and do not repeat.

Conclusion

To generate a sequence of unique random numbers in Python, you can use the `sample` function from the `random` module. This function allows you to specify the range and the number of unique random numbers you want to generate. By using `sample`, you can avoid getting duplicate numbers in your result.

0 0

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

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

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

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