Мне нужно так чтобы после генерации числа(Генерация продолжится) оно больше не генерировалось. Python
random.randint(1, 10)
Python
Python Как сделать так чтобы после сгенерированного числа оно не повторялось?
Сначала создаёшь случайную последовательность всех чисел:
arr = list(range(1, 11))
random.shuffle(arr)
А дальше просто берёшь очередное значение из arr: arr[0], arr[1], arr[2] и т. д.
arr = list(range(1, 11))
random.shuffle(arr)
А дальше просто берёшь очередное значение из arr: arr[0], arr[1], arr[2] и т. д.
Александр Дерин
Спасибо!
Максим Конуп
лучше тогда повторять arr.pop(0)
Иван Решетников
псевдо! любая последовательность чисел конечной длины имеет повторы
Ну вообще то логика тут проще некуда... Сгенерировали и поместили в массив. При следущей генерации заглядываем в этом массив через in - если уже есть там такое число - значит пропускаем шаг и генерируем новое.
Хотя конечно не оптимально (будут бесполезные повторы операций), но по логике первое что приходит в голову
Хотя конечно не оптимально (будут бесполезные повторы операций), но по логике первое что приходит в голову
>>> help(random.sample)
Help on method sample in module random:
sample(population, k) method of random.Random instance
Chooses k unique random elements from a population sequence or set.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(range(10000000), 60)
>>>
Help on method sample in module random:
sample(population, k) method of random.Random instance
Chooses k unique random elements from a population sequence or set.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(range(10000000), 60)
>>>
Похожие вопросы
- Как сделать так чтобы питон воспринимал число 13, не как 1 и 3?
- Гладкие числа. Python
- Есть ли способ вывести случайное число не используя модуль random в python
- Помогите, как сделать авторизацию в программе на python?
- Дан список чисел. Нужно посчитать количество их "пар" (т.е. "1 1 1 1 1" = 10, "1 2 3 2 3" = 2 и т.д.) (Python)
- Python задача "Игра с числами"
- Задача 10. Игра «Компьютер угадывает число» язык кода Python помогите пожалуйста
- Программа на Python, Простые Числа
- Напишите код по перебору числа на Python.
- Дружественные числа Python