Home > database >  Function that generates "n" non-repeatable nonnegative random integers and returns them in
Function that generates "n" non-repeatable nonnegative random integers and returns them in

Time:03-19

This is obviously not even close to what it says on the title.

I can't figure out how to keep generating random integers until the user input length matches the new list that was appended in a loop. And this is all I have so far, which is garbage, all I get is an empty list. I don't know if I'm close to how it should be.

Thank u in advance

Note: I know this is easily done with random.sample(range(100), k=n).

import random
n = int(input('You: '))
def random_list():
    list = []
    while list:
        a = random.randint(1, 100)
        if a not in list:
            list = list.append(a)
            if len(n) == len(list):
                break
    return list

print(random_list())

CodePudding user response:

Keeping your structure:

import random

n = int(input('You: '))

def random_list(n):
    my_list = []
    possible_numbers = list(range(1, 100))
    for _ in range(n):
        number_to_add = random.choice(possible_numbers)
        my_list.append(number_to_add)
        possible_numbers.remove(number_to_add)
    return my_list

print(random_list(n))

EDIT: I saw you mentioned the following method, i'm keeping it anyway.

Differently, you could use random.sample(seq, n) to pick a sample of dimension n from the iterable seq. I.e.:

import random

n = int(input('You: '))
possible_numbers = range(1, 100)

print(random.sample(possible_numbers, n))
  • Related