-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides-10-02.qmd
137 lines (105 loc) · 2.42 KB
/
slides-10-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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
---
title: "tuples (slides)"
format: revealjs
slide-number: true
df-print: kable
---
# CSc 110 - tuples
## Variable length parameter
Sometimes you want to handle a variable number of parameters (like `print` does)
```{python}
#| eval: true
#| echo: true
print(1, 2, 3, 4, 5)
```
## Variable length parameter
Add a `*` before your parameter name so that it accepts a variable number of arguments, gathering them into a tuple
```{python}
#| eval: true
#| echo: true
def func(*values):
print(values)
for v in values:
print(v)
def main():
func(0, 2, 'quick', 4, 'brown', 'fox')
main()
```
## Variable length parameter
Add a `*` before your parameter name so that it accepts a variable number of arguments, gathering them into a tuple
```{python}
#| eval: true
#| echo: true
def concatenate(*values):
new_string = ""
for v in values:
new_string += str(v) + " "
return new_string[:-1]
def main():
print( concatenate("The", "temperature", "is", 82, "degrees"))
main()
```
## Write a function
1. Its name is `maximum`
2. It takes a variable number of arguments: `*values`
3. It returns the highest value in `values`
```{python}
#| eval: false
#| echo: true
assert maximum(1) == 1
assert maximum(3,1) == 3
assert maximum(2,4,6) == 6
assert maximum() == None
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def maximum(*values):
max = None
for v in values:
if max == None or v > max:
max = v
return max
def main():
assert maximum(1) == 1
assert maximum(3,1) == 3
assert maximum(2,4,6) == 6
assert maximum() == None
print("Passed all tests")
main()
```
## Write a function
1. Its name is `min_max`
2. It takes a variable number of arguments: `*values`
3. It returns the highest and lowest values in `values`
Name your file `min_max_tuple.py`, submit to Gradescope.
```{python}
#| eval: false
#| echo: true
assert min_max(1) == (1, 1)
assert min_max(3,1) == (1, 3)
assert min_max(2,4,6) == (2, 6)
assert min_max() == (None, None)
```
## Write a function -- solution
```{python}
#| eval: true
#| echo: true
def min_max(*values):
max = None
min = None
for v in values:
if max == None or v > max:
max = v
if min == None or v < min:
min = v
return min, max
def main():
assert min_max(1) == (1, 1)
assert min_max(3,1) == (1, 3)
assert min_max(2,4,6) == (2, 6)
assert min_max() == (None, None)
print("Passed all tests")
main()
```