-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-Fizzbuzz.qmd
352 lines (274 loc) · 10.1 KB
/
03-Fizzbuzz.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
---
title: "Homework: Fizzbuzz"
author: Jenn Derkits
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](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](flowchart.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 <- 5
if (x %% 3 == 0 && x %% 5 == 0) {
print("FizzBuzz")
} else if (x %% 3 == 0) {
print("Fizz")
} else if (x %% 5 == 0) {
print("Buzz")
} else {
print(x)
}
```
```{python solo-fizzbuzz-py, echo = T}
x = 3
if x % 3 == 0 and x % 5 == 0:
print("FizzBuzz")
elif x % 3 == 0:
print("Fizz")
elif x % 5 == 0:
print("Buzz")
else:
print(x)
# FizzBuzz code goes here
```
Modify the code above so that the result is stored in a value `y`.
```{r solo-fizzbuzz-stored-r, echo = T}
#change the x's to y's
x <- 7
if (x %% 3 == 0 && x %% 5 == 0) {
y<-"FizzBuzz"
} else if (x %% 3 == 0) {
y<-"Fizz"
} else if (x %% 5 == 0) {
y<-"Buzz"
} 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 = 3
y = np.nan
if x % 3 == 0 and x % 5 == 0:
y = "FizzBuzz"
elif x % 3 == 0:
y = "Fizz"
elif x % 5 == 0:
y = "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.
```{r vector-fizzbuzz-r, echo = T}
xx <- 1:30
yy <- rep(NA, times = length(xx))
#add the iterative piece loop xx
#the bracket opens after the for,in and doesn't close till the very end otherwise it gives NA
for (i in 1:length(xx)){
x<- xx[i]
#the above goes through 1-30 then below looks at the conditions
if (x %% 3 == 0 && x %% 5 == 0) {
yy[i]<-"FizzBuzz"
} else if (x %% 3 == 0) {
yy[i]<-"Fizz"
} else if (x %% 5 == 0) {
yy[i]<-"Buzz"
} else {
yy[i]<-as.character(x) #convert the number to characters
}
}
# Printing the results in a data frame
res <- cbind(x = as.character(xx), result = yy)
res
```
```{python vector-fizzbuzz-py, echo = T}
import pandas as pd
import numpy as np
# Generate an array of numbers from 1 to 30
xx = np.array(range(1, 31))
yy = [np.nan] * len(xx)
# Apply the FizzBuzz logic
for i in range(len(xx)):
x = xx[i]
if x % 3 == 0 and x % 5 == 0:
yy[i] = "FizzBuzz"
elif x % 3 == 0:
yy[i] = "Fizz"
elif x % 5 == 0:
yy[i] = "Buzz"
else:
yy[i] = str(x) # Convert the number to a string/word
# Create a DataFrame with the results
res = pd.DataFrame({"x": xx, "result": yy})
# Adjust the index to start at 1
res.index = res.index + 1
# Print the DataFrame to see the results
print(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, 10)
##This is the function line 191, line 192 in the logic vector part
fizzbuzz <- function(x) {
result <- ifelse(x %% 3 == 0 & x %% 5 == 0, "FizzBuzz", ifelse(x %% 3 == 0, "Fizz", ifelse(x %% 5 == 0, "Buzz", as.character(x))))
return(result)
}
#the fizzbuzz function is applied to the vector xx
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
import numpy as np
# Generate a random list of integers between 1 and 100
xx = np.array(choices(range(1, 101), k=10))
# Define the fizzbuzz function
def fizzbuzz(x):
y = [np.nan] * len(x) # Initialize result list with NaN values
for i in range(len(x)):
if x[i] % 3 == 0 and x[i] % 5 == 0:
y[i] = "FizzBuzz"
elif x[i] % 3 == 0:
y[i] = "Fizz"
elif x[i] % 5 == 0:
y[i] = "Buzz"
else:
y[i] = str(x[i]) # Convert number to string if not divisible by 3 or 5
return y
# Apply the fizzbuzz function to the array xx
yy = fizzbuzz(x=xx)
# Create a DataFrame with the results
res = pd.DataFrame({"x": xx, "result": yy})
# Adjust the index to start at 1
res.index = res.index + 1
# Print the DataFrame to see the results
print(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}
xx <- sample(1:100, 10) # Get a random xx
yy <- rep(NA, 10)
# This is the function with the logic- is it numeric? if not don't go on...
fizzbuzz <- function(x) {
stopifnot(is.numeric(x)) # Check if x is numeric?
result <- ifelse(x %% 3 == 0 & x %% 5 == 0, "FizzBuzz",
ifelse(x %% 3 == 0, "Fizz",
ifelse(x %% 5 == 0, "Buzz", as.character(x))))
return(result)
}
# Apply the fizzbuzz function to the vector xx
yy <- fizzbuzz(x = xx)
# Print the results in a data frame
res <- cbind(x = xx, result = yy)
print(res)
```
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.
```{r function-error-fizzbuzz-r, error=TRUE}
library (dplyr)
xx <- sample(1:100, 10) # get a random xx
#xx <- sample ("hello")
##This is the function line 191, line 192 in the logic vector part
fizzbuzz <- function(x) {
# Check if x is character!! The user will get an error message as the output
if (!is.numeric (x)) {
stop("Error: Input must be numeric.")
}
#the fizzbuzz function is applied to the vector xx
result <- if_else(x %% 3 == 0 & x %% 5 == 0, "FizzBuzz",
if_else(x %% 3 == 0, "Fizz",
if_else(x %% 5 == 0, "Buzz", as.character(x))))
return(result)
}
# Printing the results in a data frame
res <- cbind(x = xx, fizbuzz = fizzbuzz (xx))
res
```
```{python function-error-fizzbuzz-py}
import pandas as pd
from random import choices
import numpy as np
#this is the 1-100 numbers
xx = np.array(choices(range(1,101), k = 10))
def fizzbuzz(x):
# Check if x is a NumPy array
# if not isinstance(x, np.ndarray):
# raise TypeError("Input must be a NumPy array.")
y = [np.nan] * len(x)
for i in range(len(x)):
if x[i] % 3 == 0 and x[i] % 5 == 0:
y[i] = "FizzBuzz"
elif x[i] % 3 == 0:
y[i] = "Fizz"
elif x[i] % 5 == 0:
y[i] = "Buzz"
else:
y[i] = str(x[i]) # Convert number to string if not divisible by 3 or 5
return y
# Apply the fizzbuzz function to the array xx
yy = fizzbuzz(x=xx)
# Create a DataFrame with the results
res = pd.DataFrame({"x": xx, "result": yy})
#start at 1
res.index = res.index + 1
# Print the DataFrame to see the results
print(res)
```