-1

I am attempting to generate a list five times using only one while loop and only one list of numbers. I have written code that seems fine to me but the list is generating once and then it generates the same list for the other tests. I want a random list everytime. I do not know what is wrong so I don't know how to tackle it. Any help would be appreciated.

Here is my code:

import random, time

number = 23
counter = 0
total = 5
counter2 = 0
current = 0
numbers = []
tally = 1
trash = []

while counter < total:
  while counter2 < number:
    for x in range(1):
      current = random.randint(1, 366)
      time.sleep(0.0001)
      counter2 += 1
      numbers.append(current)
  numbersS = set(numbers)
  size = len(numbersS)
  if size < number:
    print("1")
  else:
    print("0")
  counter += 1
  numbers = trash
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Please disregard the tally variable it is useless and I forgot to remove it before asking the question. – Jack Stokes Dec 22 '18 at 11:01
  • So you want 5 lists? What are the size of the lists to be generated? – Dani Mesejo Dec 22 '18 at 11:02
  • 1
    why not use `five_lists = [random.choices(range(1,366),k=23) for _ in range(5)]` to get 23 random numbers between 1 and 365 (inclusive) five times at _once_? – Patrick Artner Dec 22 '18 at 11:02
  • @Jack, you can edit your question and remove `tally` yourself. – trincot Dec 22 '18 at 11:05
  • You might also want to look at [how to copy or clone a list](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) ... `numbers = trash` only relables the variablename `number` to point to `trash`'s data - it does not "copy" anything – Patrick Artner Dec 22 '18 at 11:06
  • `for x in range(1):` is wasteful as well ... you do not use `x` and range(1) only runs once so no need to loop at all... – Patrick Artner Dec 22 '18 at 11:09
  • @PatrickArtner random.choices worked. Thank you. You've been very helpful. – Jack Stokes Dec 22 '18 at 11:11

1 Answers1

1

I do not know what is wrong

The line numbers = trash is not doing what you want. Instead of emptying the list it will merely make numbers a synonym for trash. This means the next time you do numbers.append(current) you actually add that value to the trash list.

Look at this simplified code and comments:

trash = []
numbers = []

numbers.append(1) # adds to numbers, not to trash

numbers = trash # now both names are synonyms for the same list; currently empty

numbers.append(2) # adds to trash(!)

numbers = trash # this was already the case: does not do anything

print(numbers, trash) # [2] [2]

You should just do numbers = [] instead of numbers = trash. Alternatively, you could stick with the same list and truncate it with del numbers[:] or numbers.clear()

trincot
  • 317,000
  • 35
  • 244
  • 286