Unit 3 Section 15 - Random Values
Fun!
- College Board Learning Objectives
- Randomization in our daily lives....
- Essential Knowledge
- Using the random library
College Board Learning Objectives
For generating random values:
- Write expressions to generate possible values
- Evaluate expressions to determine the possible results
Randomization in our daily lives....
- Rolling a dice
- Lottery Tickets
- Game of Marbles
Essential Knowledge
The exam reference sheet provides:
RANDOM(a, b) - which generates and returns a random integer from a to b, inclusive. Each result is equally likely to occur.
For example, random(1,3) could return 1, 2, or 3.
Adding two ranges to get a third range
Example Problem:
answer1 = random(0,2)
answer2 = random(1,5)
answer3 = answer1 + answer2
What is the possible range of results for answer3?
Answer!
[1, 2, 3, 4, 5, 6, 7]Working with Random Number Generators
A die contains six sides with corresponding dots 1 through 6 on individual sides. Which of the following code segments can be used to simulate the results of rolling the die 3 times and assigns the sum of the values obtained by the rolls to the variable.
A) sum = 3 * random(1,6)
B) sum = random(1,18)
C) sum = random(1,6) + random(1,6) + random(1,6)
Answer!
CRandom function in Code Segment
Answer!
C 3 1 2Using the random library
1) Using random.choice
import random
tvshows_list = ['Squid Game', 'Cobra Kai', 'Gilmore Girls', 'Sherlock Holmes', 'Barbie in the Dream House']
# pick a random choice from a list of strings.
random_tvshow = random.choice(tvshows_list)
print(f"You should watch {random_tvshow}!")
- Using random.shuffle
import random
num_list = [7,8,10,22]
print("List before using shuffle: ", num_list)
random.shuffle(num_list)
print("List after using shuffle method: ", num_list)