Python Forum
About generating N integer numbers without repetition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
About generating N integer numbers without repetition
#1
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])
Reply
#2
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)
Reply
#3
(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
Reply
#4
Thank you so much, well I wasn't expecting a function like this, good news
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Way to avoid repetition? Tuxedo 5 2,781 Feb-16-2021, 08:02 PM
Last Post: Tuxedo
  question about you want repetition this task loczeq 6 3,276 Mar-05-2020, 08:35 PM
Last Post: loczeq
  Random nr. no repetition & printing multiple lines Joey 7 2,737 Feb-05-2020, 04:23 PM
Last Post: Larz60+
  How do I name a list while generating numbers on the fly? Pleiades 6 3,227 Dec-03-2019, 05:47 PM
Last Post: jefsummers
  Generating numbers darktitan 3 2,116 Dec-01-2019, 06:25 PM
Last Post: darktitan
  Division of an integer into sub-numbers Richard_SS 4 2,884 Jun-14-2019, 11:47 AM
Last Post: DeaD_EyE
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,667 May-09-2019, 12:19 PM
Last Post: Pleiades
  20 x 20 Integer array with random numbers harryk 3 3,289 Jul-28-2018, 03:38 PM
Last Post: harryk
  List repetition ashwin 3 3,771 May-24-2017, 12:57 PM
Last Post: snippsat
  prime numbers generator is generating non prime numbers? ixaM 2 4,419 Dec-18-2016, 01:35 PM
Last Post: ixaM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020