Day 7: Hangman

How to Break a Complex Problem into a Flow Chart

Picking Random Words and Checking Answers

Step 1

Help resources

RANDOM.SAMPLE( ) We used the random.sample() list previously when we created our Password Generator. To brush up on this module: random.sample(<list_name/set>, <how_many_to_choose_from_the_list)

Python’s random module provides random.sample() function for random sampling and randomly pick more than one element from the list without repeating elements. The random.sample() returns a list of unique elements chosen randomly from the list, sequence, or set, we call it random sampling without replacement.

In simple terms, for example, you have a list of 100 names, and you want to choose ten names randomly from it without repeating names, then you must use random.sample().

random.sample(population, k)

The random.sample() function has two arguments, and both are required.

  • The population can be any sequence such as list, set from which you want to select a k length number.

  • The k is the number of random items you want to select from the sequence. k must be less than the size of the specified list.

  • A random.sample() function raises a type error if you miss any of the required arguments.

The random.sample() returns a new list containing the randomly selected item Example

import random num_list = [20, 40, 80, 100, 120] print ("Choosing 3 random items from a list using random.sample() function") new_random_list = random.sample(num_list, 3) print(sampled_list

Choosing 3 random items from a list using random.sample() function

[40. 120, 80]

RANDOM.CHOICE( ) & RANDOM.CHOICES( ) The main difference between 'sample' and 'choice', is that 'choice' only returns a SINGLE item from a list UNLESS you use the random.choices( ) function. This can return multiple items AND CAN also return REPEATED items OR it CAN REPEAT ELEMENTS

import random numbers = list(range(10)) print(random.choices(numbers, 10)) Output [3, 6, 8, 4, 2, 1, 0, 5, 9, 7] AN INTERESTING DIFFERENCE BETWEEN CHOICES AND SAMPLE (APART FROM THE ABOVE COMPARISON IS THAT WITH CHOICES YOU CAN GET MORE RETURNS THAN WHAT IS INITIALLY IN THE LIST> FOR EXAMPLE:

Last updated

Was this helpful?