Answer the question
In order to leave comments, you need to log in
How to generate random numbers?
Help implement the generation of 10 random numbers (9 to 9 characters long) that do not repeat among themselves. All this should be on a separate html page.
The whole idea sounds like this: I click on the "Generate numbers" button, I am redirected to a page on which a list of 10 numbers has already appeared.
All answers which found, a little do not correspond to that it is necessary for me.
I will be grateful for any helpful answer.
Answer the question
In order to leave comments, you need to log in
Either you have not defined something, or the question is trivial (if you count the mysterious phrase "10 random numbers (length from 9 to 9 characters )").
We generate a number in the range from 0 to 999999999. We
check its non-recurrence among previously generated ones (of which there are no more than 10). If it is unique, we add it to the list.
import random
num_list=[]
while len(num_list)<10:
num=str(random.randint(0,999999999)).zfill(9)
if not num in num_list:
num_list.append(num)
print (num_list)
['936581612', '321889578', '969427733', '735243872', '700272151', '018002065', '721644810', '501566972', '283087031', '6642']
Create a new map or, better, a new set object, add the generated value there until ten are typed. Before adding, check if there is such a thing inside, otherwise re-generate. This is literally a while loop set.size < 10.
Separate html is a separate page on the server, generated in real time from a script, a few I know will not work. You can write the generated values to cookies, session or localstorage, I think cookies are suitable and the most stable. After going to this pre-prepared page, read your knowledge and display it to the user, or if they are not there, write that cookies are used here, let them turn it on.
As for the generation itself, just random array elements with characters or character codes, there are many options on the Internet.
I am a beginner programmer, do not judge strictly.
This option saves everything to a text document. But I think you can easily adapt to your needs
import random
def generator(r): # r = количество номеров на выходе
for k in range(r):
numbers = [] # Объявляем массив, в который будут закидываться генерируемые значения
for i in range(9): # range(Х), Х = количество требуемых цифр
j = random.randint(0, 9) # Собственно сам генератор
numbers.append(j) # Добавляем сгенерированное число в массив
str_num = ''.join(map(str, numbers)) # Переводим полученный массив в строку
with open('test.txt', 'a+') as f: # Открываю файл(вместо "а+" нужно поставить "w")
f.write(str(str(str_num) + '\n') # Записываю в файл построчно
# Проверка на уникальность из текстового документа
def unicle():
with open('test.txt', 'r') as f: # Снова открываем, только уже в режиме чтения
num = f.readlines() # Считываем строки в массив
num1 = 0
i = 0 # счётчик
s = len(num) # Определяем, сколько в полученном массиве номеров
while i < s: # Ключевой цикл для проверки на уникальность
n1 = num[num1] # Выбираем объект из массива
while num.count(n1) > 1: # Проверка на наличие копий
num.remove(n1) # Если да - удаляем номер (новый не генерируется)
i += 1 # Увеличиваем счётчик дополнительно при удалении, чтобы не возникло ошибок из-за уменьшения количества строк
i += 1 # Основной счётчик +1
num1 += 1 # Переход к следующему элементу из массива
str_num = ''.join(map(str, num)) # Переводим массив в строку
with open('test.txt', 'r+') as f:
f.write(str(str_num)) # Перезаписываем результаты в этот же документ
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question