1

I have a simple python code to create random numbers, here it is

import random
for x in range(100):
    print (random.randint(1,100))

even though this code creates random numbers it can still create duplicates, can anyone help me out with an idea to make it not be able to print duplicates?

R4nsomW4re
  • 97
  • 1
  • 1
  • 6

3 Answers3

3

Generate the numbers first, then shuffle them, and pick from that list.

import random

numbers = list(range(100))  # `numbers` is now a list [0, 1, ..., 99] 
random.shuffle(numbers)  # the list is now in random order

while numbers:  # While there are numbers left, 
    a = numbers.pop()  # take one from the list,
    print(a)  # and print it.
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
AKX
  • 152,115
  • 15
  • 115
  • 172
0

You could store the random number it just generated into a list and then iterate through the list each time you go to generate another number. If the newly generated number exists within the list scrap it and go for another generation.

That's my best guess but I won't be writing you any code, it's best that you figure that out and learn. If you do need a code example let me know and I can make one for you.

  • 1
    A `set` would be a better data structure to hold the numbers already seen. Iterating over a list is O(n) complexity, while a `set` in Python is far less. – AKX Aug 04 '18 at 20:04
  • I don't believe I have ever used a set in Python. I only write code in java so I'm sure your absolutely correct. Thank you for the correction. –  Aug 04 '18 at 20:06
  • 1
    Even in Java, a set-like structure (a `HashSet`, I think? It's been a while since I've done Java) would be better than a list, I believe. :) – AKX Aug 04 '18 at 20:08
  • i will try this – R4nsomW4re Aug 04 '18 at 20:09
  • Sounds great please let me know how it works out for you if at all! :) –  Aug 06 '18 at 00:38
0
import random


mySet = set()

totalTries = 20
for i in range(totalTries):
    mySet.add(random.randint(0, 20))
###................................

_ = [print(str(x) + ", ", end="") for x in mySet]
print("\n")
print(str(totalTries - len(mySet)) + "  duplicates were dropped!")