Python Forum
About generating N integer numbers without repetition - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: About generating N integer numbers without repetition (/thread-7920.html)



About generating N integer numbers without repetition - Otbredbaron - Jan-30-2018

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])



RE: About generating N integer numbers without repetition - ODIS - Jan-30-2018

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)



RE: About generating N integer numbers without repetition - Gribouillis - Jan-30-2018

(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


RE: About generating N integer numbers without repetition - Otbredbaron - Jan-30-2018

Thank you so much, well I wasn't expecting a function like this, good news