简体   繁体   中英

Generate list of 5 non-repeating integers

I'm new to Python and I am trying to generate a list of 4 random numbers with integers between 1 and 9. The list must contain no repeating integers.

The issue I am having is that the program doesn't output exactly 4 numbers everytime. Sometimes it generates 3 numbers or 2 numbers and I can't figure out how to fix it.

My code:

import random
lst = []
for i in range(5):
     r = random.randint(1,9)
     if r not in lst: lst.append(r)
print(lst)

Is there a way to do it without the random.sample? This code is part of a larger assignment for school and my teacher doesn't want us using the random.sample or random.shuffle functions.

Your code generates 5 random numbers, but they are not necessarily unique. If a 2 is generated and you already have 2 in list you don't append it, while you should really be generating an alternative digit that hasn't been used yet.

You could use a while loop to test if you already have enough numbers:

result = []  # best not to use list as a variable name!
while len(result) < 5:
    digit = random.randint(1, 9)
    if digit not in result:
        result.append(digit)

but that's all more work than really needed, and could in theory take forever (as millions of repeats of the same 4 initial numbers is still considered random). The standard library has a better method for just this task.

Instead, you can use random.sample() to take 5 unique numbers from a range() object:

result = random.sample(range(1, 10), 5)

This is guaranteed to produce 5 values taken from the range, without duplicate digits, and it does so in 5 steps.

Use random.sample :

import random
random.sample(range(1, 10), 4)

This generates a list of four random values between 1 to 9 with no duplicates.

Your issue is, you're iterating 5 times, with a random range of 1-9. That means you have somewhere in the neighborhood of a 50/50 chance of getting a repeat integer, which your conditional prevents from being appended to your list.

This will serve you better:

def newRunLst():
     lst = []
     while len(lst) < 4:
          r = random.randint(1,9)
          if r not in lst: lst.append(r)
     print lst

if random list needed is not too small (compared to the total list) then can

  1. generate an indexed DataFrame of random numbers
  2. sort it and
  3. select from the top ... like
(pd.DataFrame([(i,np.random.rand()) for i in range(10)]).sort_values(by=1))[0][:5].sort_index()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM