Python Forum
Generate unique random numbers from different lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Generate unique random numbers from different lists
#1
Hi Guys,

My objective is to select 5 unique random numbers from a range of numbers inside a list, prior to storing them inside a final list. These 5 random numbers shall not be numbers from another list. However, my code below doesn't have the desired outcome that I want to achieve. Please advise me based on my code below. Thank you in advance.

import random

# The "outcast_list" list contains numbers to be filtered off.
outcast_list = [1, 2, 3, 4, 5]

# The "whole_list" list contains numbers that the generated number shall randomly choose from.
whole_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

selection_list = []
status = False

# Create a loop until the "status" turns True (i.e. when the list of randomized numbers has 5 numbers inside it.).
while status is False:
	# Generate one random from the "whole_list" one at a time.
	i = random.sample(whole_list, 1)

	# Create the following 3 conditions before adding the number into the "selection_list" list.
	if (i not in outcast_list) and (i not in selection_list) and (status is False):
		selection_list.append(i)

	# Break out of the "while" loop when the "selection_list" has 5 numbers inside it.
	if len(selection_list) == 5:
		status = True
		break

print(selection_list)

# Execution outcome: [[10], [3], [8], [4], [7]]
# Desired outcome: [6, 7, 8, 9, 10]
Reply
#2
You are getting a list out of random.sample, not an integer. Therefore it's not in the list of integers you are checking against, and you get a list of lists rather than a list of integers. Put [0] at the end of line 15 to get the integer out.

Is there some reason you are not just making a list that excludes the outcasts and taking a sample from that?

valid = [x for x in whole_list if x not in outcast_list]
selection_list = random.sample(valid, 5)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(May-24-2019, 05:24 PM)ichabod801 Wrote: You are getting a list out of random.sample, not an integer. Therefore it's not in the list of integers you are checking against, and you get a list of lists rather than a list of integers. Put [0] at the end of line 15 to get the integer out.

Is there some reason you are not just making a list that excludes the outcasts and taking a sample from that?

valid = [x for x in whole_list if x not in outcast_list]
selection_list = random.sample(valid, 5)


Thanks for the prompt reply and explanation, mate! I also just realized this returning "list" instead of "int" issue, a few minutes ago, while debugging. As I'm new to Python and not well versed to coding in "short form" like yours, I amended my code as follows.

import random

# The "outcast_list" list contains numbers to be filtered off.
outcast_list = [1, 2, 3, 4, 5, 6]

# The "whole_list" list contains numbers that the generated number shall randomly choose from.
whole_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

selection_list = []
status = False

# Create a loop until the "status" turns True (i.e. when the list of randomized numbers has 5 numbers inside it.).
while status is False:
	# Generate one random from the "whole_list" one at a time.
	i_list = random.sample(whole_list, 1)
	i = int(i_list[0])

	# Create the following 3 conditions before adding the number into the "selection_list" list.
	if (i not in outcast_list) and (i not in selection_list) and (status is False):
		selection_list.append(i)

	# Break out of the "while" loop when the "selection_list" has 5 numbers inside it.
	if len(selection_list) == 5:
		status = True
		break

print(selection_list)
Reply
#4
Some tips on your code: since everything in whole_list is an int, you don't need to convert them to an in on line 16. Also, you are not really using status. You break out of the while loop, so it doesn't end because you change status to True. And when you check status on line 19 it is necessarily False. The only time it is True is right before you break out of the loop that line 19 is in. I would change line 13 to while len(selection_list) < 5:. Then you can remove lines 22-25 and remove status from line 19.

Here's a not-so-short form of my solution, if it helps:

valid = []
for number in whole_list:
    if number not in outcast_list:
        valid.append(number)
selection_list = random.sample(valid, 5)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
(May-24-2019, 05:58 PM)ichabod801 Wrote: Some tips on your code: since everything in whole_list is an int, you don't need to convert them to an in on line 16. Also, you are not really using status. You break out of the while loop, so it doesn't end because you change status to True. And when you check status on line 19 it is necessarily False. The only time it is True is right before you break out of the loop that line 19 is in. I would change line 13 to while len(selection_list) < 5:. Then you can remove lines 22-25 and remove status from line 19.

Here's a not-so-short form of my solution, if it helps:

valid = []
for number in whole_list:
    if number not in outcast_list:
        valid.append(number)
selection_list = random.sample(valid, 5)

Thanks for the tips. It actually took me a while to understand why I shouldn't use boolean (i.e. status) to check the validity. Just to understand more on using boolean to check for status, can you please share with me more by quoting an example (with code snippet)?
Reply
#6
As an example, here's your for loop redone:

while len(selection_list) < 5:
    # Note that if you are just selecting one item, random.choice returns the item, not a list
    i = random.choice(whole_list)
 
    # We no longer need to check status, just outcasts and what's already been selected.
    if (i not in outcast_list) and (i not in selection_list):
        selection_list.append(i)
 
    # We no longer need to check for a break, because the while loop will do that
Right after every append, it goes back to the while statement. The while statement checks the current length. If we don't have five items yet, it does the loop again. If we have five or more, it skips to the end of the loop and continues on with the rest of the program. The loop is directly testing the termination condition, rather than getting it through the proxy of status.

That works here, because the termination condition is simple. If you have to do some processing to get the condition, so you use a conditional with a break, like you did:

while True:
    choice = input('Please select a menu item: ')
    if is_valid(choice):
        break
    print('That is not a valid selection.')
Here, we need to get the user input, and also check it for validity, before we can be sure it's time to exit the loop. But again, we don't need the proxy of status, we just check the validity of the choice, and then exit the loop if the choice is valid.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  random numbers, randint janeik 2 526 Nov-27-2023, 05:17 PM
Last Post: janeik
  Sample random, unique string pairs from a list without repetitions walterwhite 1 401 Nov-19-2023, 10:07 PM
Last Post: deanhystad
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,013 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  Generate lists of devices and partitions from /proc/partitions? DachshundDigital 1 730 Feb-28-2023, 10:55 PM
Last Post: deanhystad
  List of random numbers astral_travel 17 2,533 Dec-02-2022, 10:37 PM
Last Post: deanhystad
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,430 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Generate random id (please help!) Kjaglewicz 8 1,878 Aug-29-2022, 09:37 AM
Last Post: fracjackmac
  generating random string unique forever Skaperen 5 2,286 Aug-20-2021, 07:15 AM
Last Post: Gribouillis
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 2,758 Aug-11-2021, 03:45 PM
Last Post: jamesaarr
  Generate random hex number ZYSIA 1 11,319 Jul-16-2021, 09:21 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020