random (class slides)

CSC 110 – Generating Random Numbers and Other Important Functions and Methods

Announcements

  • Check D2L and gradescope for grades
  • 36.6% of your grade is in at this point in the semester

random module

We need to import the module random

What do the functions .random() and .randint() return?

import random

n = random.random()
print(n)

n = random.randint(0, 9)
print(n)
0.3075644665076249
3

Write a function

  1. Function name is pick_winner
  2. It takes a list as argument
  3. It generates a random index, and returns the item at that position
winner = pick_winner(["Peter", "Joan", "Mary", "June"])
print(winner)

Write a function – solution

import random

def pick_winner(names):
  index = random.randint(0, len(names) - 1)
  return names[index]

if __name__ == "__main__":
  winner = pick_winner(["Peter", "Joan", "Mary", "June"])
  print(winner)
Mary

Setting a seed

What happens when you run pick_winner multiple times?

To get always the same result (for autograding purposes, for example) we can set a seed.

import random

def pick_winner(names):
  index = random.randint(0, len(names) - 1)
  return names[index]

if __name__ == "__main__":
  random.seed(123)
  winner = pick_winner(["Peter", "Joan", "Mary", "June"])
  print(winner)
Peter

Changing a list with random numbers

Write a function that takes as argument a list of integers. Iterate over each list element (with a while loop), replacing each integer with a random number between zero and the original integer.

Test case:

numbers = [3, 2, 1, 3, 5]
numbers = random_list(numbers)
print(numbers)
[0, 1, 0, 3, 2]

Submit for gradescope attendance

Submit your random_list to gradescope.

Name your file random_list.py and remember to set the seed to 123 inside your function.