Генератор неповторяющихся чисел python

Python 3: Генерация случайных чисел (модуль random)¶

Python порождает случайные числа на основе формулы, так что они не на самом деле случайные, а, как говорят, псевдослучайные [1]. Этот способ удобен для большинства приложений (кроме онлайновых казино) [2].

[1] Википедия: Генератор псевдослучайных чисел
[2] Доусон М. Программируем на Python. — СПб.: Питер, 2014. — 416 с.: ил. — 3-е изд

Модуль random позволяет генерировать случайные числа. Прежде чем использовать модуль, необходимо подключить его с помощью инструкции:

random.random¶

random.random() — возвращает псевдослучайное число от 0.0 до 1.0

random.random() 0.07500815468466127 

random.seed¶

random.seed() — настраивает генератор случайных чисел на новую последовательность. По умолчанию используется системное время. Если значение параметра будет одиноким, то генерируется одинокое число:

random.seed(20) random.random() 0.9056396761745207 random.random() 0.6862541570267026 random.seed(20) random.random() 0.9056396761745207 random.random() 0.7665092563626442 

random.uniform¶

random.uniform(, ) — возвращает псевдослучайное вещественное число в диапазоне от до :

random.uniform(0, 20) 15.330185127252884 random.uniform(0, 20) 18.092324756265473 

random.randint¶

random.randint(, ) — возвращает псевдослучайное целое число в диапазоне от до :

random.randint(1,27) 9 random.randint(1,27) 22 

random.choince¶

random.choince() — возвращает случайный элемент из любой последовательности (строки, списка, кортежа):

random.choice('Chewbacca') 'h' random.choice([1,2,'a','b']) 2 random.choice([1,2,'a','b']) 'a' 

random.randrange¶

random.randrange(, , ) — возвращает случайно выбранное число из последовательности.

Читайте также:  Hex питон что это

random.shuffle¶

random.shuffle() — перемешивает последовательность (изменяется сама последовательность). Поэтому функция не работает для неизменяемых объектов.

List = [1,2,3,4,5,6,7,8,9] List [1, 2, 3, 4, 5, 6, 7, 8, 9] random.shuffle(List) List [6, 7, 1, 9, 5, 8, 3, 2, 4] 

Вероятностные распределения¶

random.triangular(low, high, mode) — случайное число с плавающей точкой, low ≤ N ≤ high . Mode — распределение.

random.betavariate(alpha, beta) — бета-распределение. alpha>0 , beta>0 . Возвращает от 0 до 1.

random.expovariate(lambd) — экспоненциальное распределение. lambd равен 1/среднее желаемое. Lambd должен быть отличным от нуля. Возвращаемые значения от 0 до плюс бесконечности, если lambd положительно, и от минус бесконечности до 0, если lambd отрицательный.

random.gammavariate(alpha, beta) — гамма-распределение. Условия на параметры alpha>0 и beta>0 .

random.gauss(значение, стандартное отклонение) — распределение Гаусса.

random.lognormvariate(mu, sigma) — логарифм нормального распределения. Если взять натуральный логарифм этого распределения, то вы получите нормальное распределение со средним mu и стандартным отклонением sigma . mu может иметь любое значение, и sigma должна быть больше нуля.

random.normalvariate(mu, sigma) — нормальное распределение. mu — среднее значение, sigma — стандартное отклонение.

random.vonmisesvariate(mu, kappa) — mu — средний угол, выраженный в радианах от 0 до 2π, и kappa — параметр концентрации, который должен быть больше или равен нулю. Если каппа равна нулю, это распределение сводится к случайному углу в диапазоне от 0 до 2π.

random.paretovariate(alpha) — распределение Парето.

random.weibullvariate(alpha, beta) — распределение Вейбулла.

Примеры¶

Генерация произвольного пароля¶

Хороший пароль должен быть произвольным и состоять минимум из 6 символов, в нём должны быть цифры, строчные и прописные буквы. Приготовить такой пароль можно по следующему рецепту:

import random # Щепотка цифр str1 = '123456789' # Щепотка строчных букв str2 = 'qwertyuiopasdfghjklzxcvbnm' # Щепотка прописных букв. Готовится преобразованием str2 в верхний регистр. str3 = str2.upper() print(str3) # Выведет: 'QWERTYUIOPASDFGHJKLZXCVBNM' # Соединяем все строки в одну str4 = str1+str2+str3 print(str4) # Выведет: '123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM' # Преобразуем получившуюся строку в список ls = list(str4) # Тщательно перемешиваем список random.shuffle(ls) # Извлекаем из списка 12 произвольных значений psw = ''.join([random.choice(ls) for x in range(12)]) # Пароль готов print(psw) # Выведет: '1t9G4YPsQ5L7'

Этот же скрипт можно записать всего в две строки:

import random print(''.join([random.choice(list('123456789qwertyuiopasdfghjklzxc vbnmQWERTYUIOPASDFGHJKLZXCVBNM')) for x in range(12)])) 

Данная команда является краткой записью цикла for, вместо неё можно было написать так:

import random psw = '' # предварительно создаем переменную psw for x in range(12): psw = psw + random.choice(list('123456789qwertyuiopasdfgh jklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM')) print(psw) # Выведет: Ci7nU6343YGZ 

Данный цикл повторяется 12 раз и на каждом круге добавляет к строке psw произвольно выбранный элемент из списка.

Ссылки¶

Источник

How to generate non-repeating random numbers in Python?

In this article, we will show you how to generate non-repeating random numbers in python. Below are the methods to accomplish this task:

  • Using randint() & append() functions
  • Using random.sample() method of given list
  • Using random.sample() method of a range of numbers
  • Using random.choices() method

Using randint() & append() functions

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword, to import the random module.
  • Create an empty list which is the resultant random numbers list.
  • Use the for loop, to traverse the loop 15 times.
  • Use the randint() function(Returns a random number within the specified range) of the random module, to generate a random number in the range in specified range i.e, from 1 to 100.
  • Use the if conditional statement to check whether the generated random number is not in the resultant randomList with the not and in operators.
  • Use the append() function( adds the element to the list at the end) to append the random number to the resultant list, if the condition is true.
  • Print the resultant random numbers list

Example

The following program returns the non-repeating random numbers using the randint(), append() functions −

# importing random module import random # resultant random numbers list randomList=[] # traversing the loop 15 times for i in range(15): # generating a random number in the range 1 to 100 r=random.randint(1,100) # checking whether the generated random number is not in the # randomList if r not in randomList: # appending the random number to the resultant list, if the condition is true randomList.append(r) # printing the resultant random numbers list print("non-repeating random numbers are:") print(randomList)

Output

On executing, the above program will generate the following output −

non-repeating random numbers are: [84, 86, 90, 94, 59, 33, 58, 36, 62, 50, 26, 38, 4, 89]

Using random.sample() method of given list

The random.sample() method returns a list containing a randomly selected number of elements from a sequence.

Syntax

Parameters

  • sequence(required) − any sequence like list, tuple etc
  • k(optional) − The length of the returned list as an integer

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword, to import the random module.
  • Create a variable to store an input list.
  • Use the set() function(returns all the distinct items from an iterable and converts an iterable to set), to remove the repeating elements from the input list.
  • Use the list() function(converts the sequence/iterable to a list), to convert the above set into a list. Now the list has only unique elements.
  • Use the sample() function by passing the list containing unique items, k value as arguments to it to print the k(here 4) random numbers from the list which are nonrepeating.

Example

The following program returns the 4 non-repeating random numbers using the random.sample() function −

# importing random module import random # input list inputList = [1, 2, 3, 1, 4, 3, 5, 7, 9, 8, 2, 3] # removing repeating elements from the list using the set() function resultSet=set(inputList) # converting the set into a list(now the list has only unique elements) uniqueList =list(resultSet) # printing 4 random numbers from the list which is non-repeating print("4 non-repeating random numbers from the list are:") print(random.sample(uniqueList, 4))

Output

On executing, the above program will generate the following output −

4 non-repeating random numbers from the list are: [7, 2, 4, 8]

Using random.sample() method of a range of numbers

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword, to import the random module.
  • Get the numbers in the specified range i.e, here 1 to 100 using the range() function(The range() function returns a sequence of numbers that starts at 0 and increments by 1 (default) and stops before a given number).
  • Use the sample() function by passing the given range of numbers list, k value as arguments to it to print the k(here 4) random numbers from the list which are nonrepeating.

Example

The following program returns the 4 non-repeating random numbers using the random.sample() function −

# importing random module import random # getting numbers from 0 to 100 inputNumbers =range(0,100) # printing 4 random numbers from the given range of numbers which are # non-repeating using sample() function print("4 non-repeating random numbers are:") print(random.sample(inputNumbers, 4))

Output

On executing, the above program will generate the following output −

4 non-repeating random numbers are: [67, 50, 61, 47]

Using random.choices() method

The random module contains the random.choices() method. It is useful to select multiple items from a list or a single item from a specific sequence.

Syntax

Parameters

  • sequence(required) − any sequence like list, tuple etc
  • k(optional) − The length of the returned list as an integer

Example

The following program returns the 4 non-repeating random numbers using the random.choices() function −

# importing random module import random # getting numbers from 0 to 100 inputNumbers =range(0,100) # printing 4 random numbers from the given range of numbers which are # non-repeating using choices() function print("4 non-repeating random numbers are:") print(random.choices(inputNumbers, k=4))

Output

On executing, the above program will generate the following output −

4 non-repeating random numbers are: [71, 4, 12, 21]

Conclusion

In this tutorial, we learned how to generate non-repeating numbers in Python using four different ways. We learned how to generate non-repeating numbers that are not on the list. We learned How to determine whether an element is included in a list in order to generate non-repeating integers.

Источник

Generate random numbers without repetition in Python

In this tutorial, we will learn how to get non-repeating random numbers in Python. There is no in-built function to perform this task. But, we can use some techniques to do this. We will discuss these methods in this tutorial.

Methods we use in this tutorial:

These two methods take a list as input and select k(input) random elements and return them back. To get non-repeating elements we give a list as input where there are no repeating elements. Even if we already have a list with repeating elements we can convert it to set and back to list this will remove repeating elements. If we don’t have a list and get elements between two numbers we can do that using the range() function.

Using random.sample() example 1:

random.sample() is an in-built function of Python that gives us a list of random elements from the input list.

#importing required libraries import random li=[10,20,30,40,20,30,60,50,60] #converting list to set so that to remove repeating elements se=set(li) li=list(se) #we use this list to get non-repeating elemets print(random.sample(li,3))

Example 2:

Using range() function. This function gives a list of non-repeating elements between a range of elements.

#importing required libraries import random li=range(0,100) #we use this list to get non-repeating elemets print(random.sample(li,3))

Using random.choices() example 3:

random.choices() is an in-built function in Python. This method takes 2 arguments a list and an integer. This returns a list of a given length that is selected randomly from the given list.

#importing required libraries import random li=[10,20,30,40,20,30,60,50,60] #converting list to set so that to remove repeating elements se=set(li) li=list(se) #we use this list to get non-repeating elemets print(random.choices(li,k=3))

Example 4:

#importing required libraries import random li=range(0,100) #we use this list to get non-repeating elemets print(random.choices(li,k=3))

Источник

Оцените статью