-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.qmd
336 lines (269 loc) · 8.27 KB
/
index.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
---
title: "Homework: Fizzbuzz"
author: "Riddhimoy Ghosh"
format: html
---
Instructions:
- You can answer the questions below in either R or Python. I will give you 50% extra credit if you provide answers in both languages. Otherwise, please feel free to delete the code chunks corresponding to the language you don't wish to work in.
- Once you have finished this assignment, render the document (Ctrl/Cmd-Shift-K or the Render button).
- Commit the qmd file and any other files you have changed to the repository and push your changes.
- In Canvas, submit a link to your github repository containing the updated files.
# Introduction to Fizzbuzz
The "FizzBuzz Test" is a famous programming interview question.
> Write a program that prints the numbers from 1 to 30. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"
Start by filling in the following table for the numbers 1:30 manually, to get a feel for the task.
| Input | Output |
|-------|------------|
| 1 | 1 |
| 2 | 2 |
| 3 | 'Fizz' |
| 4 | 4 |
| 5 | 'Buzz' |
| 6 | 'Fizz' |
| 7 | 7 |
| 8 | 8 |
| 9 | 'Fizz' |
| 10 | 'Buzz' |
| 11 | 11 |
| 12 | 'Fizz' |
| 13 | 13 |
| 14 | 14 |
| 15 | 'FizzBuzz' |
| 16 | 16 |
| 17 | 17 |
| 18 | 'Fizz' |
| 19 | 19 |
| 20 | 'Buzz' |
| 21 | 'Fizz' |
| 22 | 22 |
| 23 | 23 |
| 24 | 'Fizz' |
| 25 | 'Buzz' |
| 26 | 26 |
| 27 | 'Fizz' |
| 28 | 28 |
| 29 | 29 |
| 30 | 'FizzBuzz' |
: Fizzbuzz for 1:30
On paper or using a tool such as <https://excalidraw.com>, create a program flow map for the sequence of if-statements you need to evaluate for fizzbuzz. Add the picture to the folder containing this file, and name the picture flowchart.png. Add the picture to Git and commit/push your changes.
![Program Flow map for FizzBuzz](flowmap.png)
In the chunk below, write code which will solve this problem for a single value `x`. You should be able to change the value of x at the top of the chunk and still get the correct answer.
```{r solo-fizzbuzz-r, echo = T}
x <- 30
# FizzBuzz code goes here
if (x%%15==0) {
print("FizzBuzz")
} else if (x%%5==0) {
print("Buzz")
} else if (x%%3==0){
print("Fizz")
} else {
print(x)
}
```
```{python solo-fizzbuzz-py, echo = T}
x = 31
# FizzBuzz code goes here
if x % 15 == 0:
print("FizzBuzz")
elif x % 5== 0:
print("Buzz")
elif x % 3== 0:
print("Fizz")
else:
print(x)
```
Modify the code above so that the result is stored in a value `y`.
```{r solo-fizzbuzz-stored-r, echo = T}
x <- 30
y <- NA
# FizzBuzz code goes here
if (x%%15==0) {
y= "FizzBuzz"
} else if (x%%5==0) {
y = "Buzz"
} else if (x%%3==0){
y = "Fizz"
} else {
y = x
}
print(paste("For x = ", x, " my code produces ", y, sep = ""))
```
```{python solo-fizzbuzz-stored-py, echo = T}
import numpy as np
x = 15
y = np.nan
# FizzBuzz code goes here
if x%15==0:
y= "FizzBuzz"
elif x%5==0:
y = "Buzz"
elif x%3==0:
y = "Fizz"
else:
y = x
print("For x = "+ str(x)+ " my code produces "+ str(y))
```
# A vector of FizzBuzz
The code in the previous problem only solves FizzBuzz for a single value of `x`. Extend your code using a loop so that it will work for all values in a vector `xx`, storing values in a corresponding vector `yy`.
You can copy/paste code from previous chunks to make this chunk easier.
```{r vector-fizzbuzz-r, echo = T}
xx <- 1:30
yy <- rep(NA, times = 30)
# FizzBuzz code goes here
for (i in 1: length(xx)){
if (xx[i]%%15==0) {
yy[i] <- "FizzBuzz"
} else if (xx[i]%%5==0) {
yy[i] <- "Buzz"
} else if (xx[i]%%3==0){
yy[i] <- "Fizz"
} else {
yy[i] = xx[i]
}
}
# Printing the results in a data frame
res <- cbind(x = xx, result = yy)
res
```
```{python vector-fizzbuzz-py, echo = T}
import pandas as pd
xx = np.array(range(30)) + 1
yy = [np.nan]*30
# FizzBuzz code goes here
for i in range(len(xx)):
if xx[i] %15==0:
yy[i] = "FizzBuzz"
elif xx[i]%5==0:
yy[i] = "Buzz"
elif xx[i]%3==0:
yy[i] = "Fizz"
else:
yy[i] = xx[i]
# Printing the results in a data frame
res = pd.DataFrame({"x": xx, "result": yy})
res
```
# Functions and FizzBuzz
In the previous question, you extended your fizzbuzz code to iterate through a vector `xx` and produce a result `yy`. Can you generalize this, writing a function `fizzbuzz` that takes a variable `x` and returns a corresponding fizzbuzzified variable? Your function should be able to handle `x` that is a vector or a scalar value, and should store your solution in `yy`.
```{r function-fizzbuzz-r}
xx <- sample(1:100, 10) # get a random xx
yy <- rep(NA, length(xx))
fizzbuzz <- function(x) {
y<-c()
# Your code goes here
for (i in 1: length(xx)){
if (x[i]%%15==0) {
y[i] <- "FizzBuzz"
} else if (x[i]%%5==0) {
y[i] <- "Fizz"
} else if (x[i]%%3==0){
y[i] <- "Buzz"
} else {
y[i] <- x[i]
}
}
return(y)
}
yy <- fizzbuzz(x = xx)
# Printing the results in a data frame
res <- cbind(x = xx, result = yy)
res
```
```{python function-fizzbuzz-py}
import pandas as pd
from random import choices
xx = np.array(choices(range(100), k = 10)) + 1
# xx =3
def fizzbuzz(x):
if np.isscalar(x):
x = np.array([x])
y = [np.nan]*len(x) # this just defines something to return
# Your code goes here
for i in range(len(x)):
if x[i] %15==0:
y[i] = "FizzBuzz"
elif x[i]%5==0:
y[i] = "Buzz"
elif x[i]%3==0:
y[i] = "Fizz"
else:
y[i] = x[i]
return y
yy = fizzbuzz(x = xx)
# Printing the results in a data frame
res = pd.DataFrame({"x": xx, "result": yy})
res
```
# Defensive Programming
You cannot always assume that the person using your functions knows what they're doing. Add a check to the function you wrote in the last question so that it will handle non-numeric input by issuing an error message.
In R, you can use the function [`stopifnot()` to halt function execution if there is an error](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/stopifnot); this will give you a basic error message.
```{r stopifnotdemo, error = T}
stopifnot(2 > 3)
```
In Python, you can use a [`try:` statement with a `except:` clause](https://docs.python.org/3/tutorial/errors.html#handling-exceptions). This functions like an if-else statement, where if no error occurs, the except statement is never executed.
```{python tryexceptdemo, error = T}
try:
int(32)
except ValueError:
print("Error: could not turn value into an integer")
```
See more examples of this in the [Input Validation](https://srvanderplas.github.io/stat-computing-r-python/part-gen-prog/05-functions.html#input-validation) section of the textbook.
```{r function-error-fizzbuzz-r}
xx <- sample(1:100, 10) # get a random xx
# xx<-c(1,2,"crazy")
yy <- rep(NA, 10)
fizzbuzz <- function(x) {
y<-c()
# Your code goes here
for (i in 1: length(xx)){
# if expression is FALSE, the string (in this case "There is a non numeric entry # ...) is used as part of the error message
stopifnot("There is a non numeric entry in the input vector!" = class(xx[i]) %in% c("integer", "numeric"))
if (x[i]%%15==0) {
y[i] <- "FizzBuzz"
} else if (x[i]%%5==0) {
y[i] <- "Fizz"
} else if (x[i]%%3==0){
y[i] <- "Buzz"
} else {
y[i] <- x[i]
}
}
return(y)
}
yy <- fizzbuzz(x = xx)
# Printing the results in a data frame
res <- cbind(x = xx, result = yy)
res
```
```{python function-error-fizzbuzz-py}
import pandas as pd
from random import choices
xx = np.array(choices(range(100), k = 10)) + 1
# xx = (1,3,5,"crazy",7)
# xx = 1
def fizzbuzz(x):
if np.isscalar(x):
x = np.array([x])
y = [np.nan]*len(x) # this just defines something to return
# Your code goes here
for i in range(len(x)):
try:
value = int(x[i])
except ValueError:
print(f"Error: '{x[i]}', the {i+1}th element is not a valid integer")
continue
if value %15==0:
y[i] = "FizzBuzz"
elif value %5==0:
y[i] = "Buzz"
elif value %3==0:
y[i] = "Fizz"
else:
y[i] = value
return y
yy = fizzbuzz(x = xx)
# Printing the results in a data frame
res = pd.DataFrame({"x": xx, "result": yy})
res
```