-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.qmd
410 lines (311 loc) · 10.6 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
---
title: "Homework: Fizzbuzz"
author: "Dhanushka Sanjeewa"
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 | 6 |
| 7 | 7 |
| 8 | 8 |
| 9 | Fizz |
| 10 | Buzz |
| 11 | 11 |
| 12 | Fizz |
| 13 | 13 |
| 14 | 14 |
| 15 | FIzz - Buzz |
| 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 | FIzz - Buzz |
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"](Image/Diagram 01.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.
**Using R **
```{r solo-fizzbuzz-r, echo = T}
x <- 3
# FizzBuzz code goes here
if (x %% 3 == 0 & x %% 5 != 0){
print("Fizz")
}else if (x %% 3 != 0 & x %% 5 == 0){
print("Buzz")
}else if (x %% 3 == 0 & x %% 5 ==0){
print("fizz-buzz")
}else{
print(x)
}
```
Lets do it in **python** now.
```{python solo-fizzbuzz-py, echo = T}
x = 3
# FizzBuzz code goes here
if x % 3 == 0 and x % 5 != 0:
print ("Fizz")
elif x % 3 != 0 and x % 5 == 0:
print("Buzz")
elif x % 3 == 0 and x % 5 == 0:
print("Fizz-Buzz")
else:
print( x )
```
Modify the code above so that the result is stored in a value `y`.
**Using R **
```{r solo-fizzbuzz-stored-r, echo = T}
x <- 3
y <- NA
# FizzBuzz code goes here
if (x %% 3 == 0 & x %% 5 != 0){
y <- "Fizz"
}else if (x %% 3 != 0 & x %% 5 ==0){
y <- "Buzz"
}else if (x %% 3 == 0 & x %% 5 ==0){
y <- "fizz-buzz"
}else{
y <- x
}
print(paste("For x = ", x, " my code produces ", y, sep = ""))
```
Lets do it in **python** now.
```{python solo-fizzbuzz-stored-py, echo = T}
import numpy as np
x = 3
y = np.nan
# FizzBuzz code goes here
if x % 3 == 0 and x % 5 != 0:
y = "Fizz"
elif x % 3 != 0 and x % 5 == 0:
y = "Buzz"
elif x % 3 == 0 and x % 5 == 0:
y = "Fizz-Buzz"
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.
**Using R**
```{r vector-fizzbuzz-r, echo = T}
xx <- 1:30
yy <- rep(NA, times = 30) # create a vector of "NA" with length of xx.
# FizzBuzz code goes here
for (i in 1:length(xx)){
if (xx[i] %% 3 == 0 & xx[i] %% 5 != 0){
yy <- replace(yy, i, "Fizz")
}
else if (xx[i] %% 5 == 0 & xx[i] %% 3 != 0){
yy <- replace(yy, i, "Buzz")
}
else if (xx[i] %% 3 == 0 & xx[i] %% 5 ==0){
yy <- replace(yy, i, "Fizz buzz")
}
else{
z <- xx[i]
yy <- replace(yy, i, z)
}
}
# Printing the results in a data frame
res <- cbind(x = xx, result = yy)
res
```
Lets do it in **python** now.
```{python vector-fizzbuzz-py, echo = T}
import pandas as pd
import numpy as np
xx = np.array(range(30)) + 1
yy = [np.nan]*30 ### create an array of "NA" with length of xx.
# FizzBuzz code goes here
for i in range(0,len(xx)):
if xx[i] % 3 == 0 and xx[i] % 5 != 0:
yy[i] = "Fizz"
elif xx[i] % 5 == 0 and xx[i] % 3 != 0:
yy[i] = "Buzz"
elif xx[i] % 5 == 0 and xx[i] % 3 == 0:
yy[i] = "Fizz-Buzz"
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`.
**Using R**
```{r function-fizzbuzz-r}
xx <- sample(1:100, 10) # get a random xx
yy <- rep(NA, 10)
fizzbuzz <- function(x) {
# code goes here
yy = rep(NA, length(x)) # create a vector that has same length as x
for (i in 1:length(x)){
if (x[i] %% 3 == 0 & x[i] %% 5 != 0){
yy <- replace(yy, i, "Fizz")
}
else if (x[i] %% 5 == 0 & x[i] %% 3 != 0){
yy <- replace(yy, i, "Buzz")
}
else if (x[i] %% 3 == 0 & x[i] %% 5 ==0){
yy <- replace(yy, i, "Fizz buzz")
}
else{
z <- x[i]
yy <- replace(yy, i, z)
}
}
return (yy)
}
yy <- fizzbuzz(x = xx)
yy
# Printing the results in a data frame
res <- cbind(x = xx, result = yy)
res
```
Lets do it in **python** now.
```{python function-fizzbuzz-py}
import pandas as pd
from random import choices
xx = np.array(choices(range(100), k = 10)) + 1
xx
def fizzbuzz(x):
y = [np.nan]*len(x) # create a vector with the same length as input, x
# code goes here
for i in range(0,len(x)):
if x[i] % 3 == 0 and x[i] % 5 != 0:
y[i] = "Fizz"
elif x[i] % 5 == 0 and x[i] % 3 != 0:
y[i] = "Buzz"
elif x[i] % 5 == 0 and x[i] % 3 == 0:
y[i] = "Fizz-Buzz"
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("hello")
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.
**Using R**
```{r function-error-fizzbuzz-r}
xx <- sample(1:100, 10) # get a random xx
yy <- rep(NA, 10)
fizzbuzz <- function(x) {
if (is.numeric(x)==FALSE){
print (" !!! Use integer values in the input vector !!!")
}
else {
x <- round(abs(x))
# code goes here
yy <- rep(NA, length(x)) # create a vector that has same length as x
for (i in 1:length(x)){
if (x[i] %% 3 == 0 & x[i] %% 5 != 0){
yy <- replace(yy, i, "Fizz")
}
else if (x[i] %% 5 == 0 & x[i] %% 3 != 0){
yy <- replace(yy, i, "Buzz")
}
else if (x[i] %% 3 == 0 & x[i] %% 5 ==0){
yy <- replace(yy, i, "Fizz buzz")
}
else{
z <- x[i]
yy <- replace(yy, i, z)
}
}
if ( typeof(x) == "double"){
cat("Warning : all non-integer numbers were rounded to the nearest integer. \n")
return(yy)
}else {
return(yy)
}
}
}
fizzbuzz(x = c(12.0,23,44.0,-15)) ## works for "doubles" if sb accidentally input any. eg: 23.0 will be identified as double
## Lets try to use string input,
x1 = c("12",4, 23,56,27)
fizzbuzz(x =x1) ## you will get an error msg here.
cat("\n") # get a new line.
# Printing the results in a data frame
yy <- fizzbuzz(x = xx)
res <- cbind(x = xx, result = yy)
res
```
Lets do it in **python** now.
```{python function-error-fizzbuzz-py}
## load the relevant packages
import numpy as np
import pandas as pd
from random import choices
# Create an array of 10 random values from 0 to 100
xx = np.array(choices(range(100), k=10)) + 1
def fizzbuzz(x):
# Check if the data type of x is either float or int
if x.dtype == "float" or x.dtype == "int":
x1 = np.round(x).astype(int)
# Create a list with the same length as input x
y = [np.nan] * len(x1)
# Apply the Fizz-Buzz logic
for i in range(len(x)):
if x1[i] % 3 == 0 and x1[i] % 5 != 0:
y[i] = "Fizz"
elif x1[i] % 5 == 0 and x1[i] % 3 != 0:
y[i] = "Buzz"
elif x1[i] % 5 == 0 and x1[i] % 3 == 0:
y[i] = "Fizz-Buzz"
else:
y[i] = x1[i]
if x.dtype == "float":
print("Warning : all non-integer numbers were rounded to the nearest integer. \n")
return y
else:
print("All elements in the input array must be numbers.", "\n")
return None
## try to use the function using a string input.
x1 = np.array(["12",3,54,23])
fizzbuzz(x = x1)
x2 = np.array([12, 34.5,23.6]) ## works for floats too
fizzbuzz(x2)
# Printing the results in a data frame
yy = fizzbuzz(x = xx)
res = pd.DataFrame({"x": xx, "result": yy})
res
```