Python Forum

Full Version: About generating N integer numbers without repetition
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody,

I wrote this small piece of code to generate N numbers without repetition.
The algorithm should be fine but since I'm learning Python I'd like to know if my code is correct and if it can be improved with better functions because I have the feeling that it's too much "C style".

import random

random.seed()

N = 10
array = list(range(1, N + 1))
i = 1
a_size = N
while a_size > 1:
    p = random.getrandbits(32)
    k = p % a_size
    print(array[k])
    array[k] = array[a_size - 1]
    a_size = a_size  - 1
print(array[0])
Hello,

you can use random.sample function. Like this:

import random

min_value = 1
max_value = 10
count = 5

random_numbers = random.sample(range(min_value, max_value), count)

print(random_numbers)
(Jan-30-2018, 03:40 AM)ODIS Wrote: [ -> ]random_numbers = random.sample(range(min_value, max_value), count)
The 'end' bound of a range is never reached in python, so you need 1 + max_value
Thank you so much, well I wasn't expecting a function like this, good news