Unwanted random iterator in For-Loop

I tried to create a function to create a given number (numbersToChoose) of values โ€‹โ€‹between two other values โ€‹โ€‹(startFrom and stopAt), but for some reason the iterator (?) In the second for-loop (line 7) in this case a seems to be randomly generated. although I see no reason for this.

def chooseRandomNumbers(numbersToChoose, startFrom, stopAt):

 numbers = [(randrange(startFrom, stopAt))]  # initialize empty list of numbers

 for n in range(numbersToChoose-1):  # choose random number from 1 to 49 a total of 7 times
    x = randrange(startFrom, stopAt+1)
    for a in numbers:  # check for already existing elements in "numbers"
        if x == numbers[a]:  # if new random number already exists in "numbers" discard and run loop again
            n -= 1  # decreases n by 1 so a new (hopefully not already existing) number can be generated
        else:  # generated numbers does not exist in "numbers" yet
            numbers.append(x)  # appends randomly chosen number to list "numbers"

 return numbers  # returns said list "numbers"

      

Any advice on how to deal with this is greatly appreciated. Also please tell me if there is anything else bad in the code possible (just started python).

+3


source to share


1 answer


Invalid code to check if the generated number is in the list. for a in numbers

, in this loop you are using numbers[a]

, and a

is a member of the list, but not the index of the member. use in

to check if a number is in the list:

from random import randrange

def chooseRandomNumbers(numbersToChoose, startFrom, stopAt):
     numbers = []
     for n in range(numbersToChoose):
        x = randrange(startFrom, stopAt+1)
        if not x in numbers:
            numbers.append(x)
        else:
            n -= 1
     return numbers

      



or simply:

from random import sample
def chooseRandomNumbers(numbersToChoose, startFrom, stopAt):
    return sample(range(startFrom,stopAt+1),numbersToChoose)

      

+2


source







All Articles