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?

0

3 Answers 3

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.
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

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.
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.
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. :)
i will try this
Sounds great please let me know how it works out for you if at all! :)
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!")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.