mercredi 18 octobre 2017

How to properly using a while loop, and append to list

I have confused myself with an elementary exercise:

I begin with a function that returns a random number between 1 and 10.

import random

def get_random_number():
    return random.randint(1,11)

Now, here's the task. A user will specify N random numbers (assume less than 10). I then wish to put these N random numbers into a list, while I make sure that don't add the same number twice to the list.

Here's how I started to do this:

empty_list = []
N= ...   ### whatever number set by the user

def reserve_numbers(reserved_list, total_numbers):
    for i in range(total_numbers):
        num = get_random_number()
        if num not in reserved_list:
            reserved_list.append(hum)
        else:
            while num in reserved_list:
                num = get_random_number()
                if num not in reserved_list:
                    reserved_list.append(hum)

## call function        
reserve_numbers(empty_list, N)

I think this function is flawed. However, the idea is this:

"For # of numbers requested: Draw a random number. If the random number isn't in the list, put it in the list. while this number is the list, draw again and keep drawing until you get a unique number. Then, put it in the list. "

My problem is after the while loop. When the while loop breaks, then it's a unique number and I should append it. I shouldn't use another if statement, right?




Aucun commentaire:

Enregistrer un commentaire