-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides-06-02.qmd
119 lines (86 loc) · 2.46 KB
/
slides-06-02.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
---
title: "random (slides)"
format: revealjs
slide-number: true
df-print: kable
---
# CSC 110 -- Generating Random Numbers and Other Important Functions and Methods
## Announcement
* Check gradescope for grades
* Lecture next Friday, Oct 11 will be on Zoom.
* You can also come here and watch the recording so that TAs can help
* Attendance window will be 9am - 9pm
## random module
We need to `import` the module `random`
What do the functions `.random()` and `.randint()` return?
```{python}
#| echo: true
import random
n = random.random() #returns a random float between 0 and 1
print(n)
n = random.randint(0, 9) #returns a random integer betweem 0 and 9.
print(n)
```
## Write a function
1. Function name is `pick_winner`
1. It takes a list as argument
1. It generates a random index, and returns the item at that position
```{python}
#| eval: false
#| echo: true
winner = pick_winner(["Peter", "Joan", "Mary", "June"])
print(winner)
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
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)
```
## 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.
```{python}
#| eval: true
#| echo: true
import random
def pick_winner(names):
random.seed(123)
index = random.randint(0, len(names) - 1)
return names[index]
if __name__ == "__main__":
winner = pick_winner(["Peter", "Joan", "Mary", "June"])
print(winner)
```
## Write a function
Write a function `random_list` that takes as argument a list of `numbers`. Iterate over each list element (with a `while` loop), replacing each integer with a random number between zero and the original number. Set the seed as `123` in your function.
Name your file `random_list.py` and submit to Gradescope.
```{python}
#| eval: false
#| echo: true
# test case
assert random_list([3, 2, 1, 3, 5]) == [0, 1, 0, 3, 2]
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
import random
def random_list(numbers):
random.seed(123)
index = 0
while index < len(numbers):
item = numbers[index]
numbers[index] = random.randint(0, item)
index += 1
return numbers
if __name__ == "__main__":
assert random_list([3, 2, 1, 3, 5]) == [0, 1, 0, 3, 2]
print("pass the test")
```