deepin中zz_如何解决R中的FizzBuzz问题
deepin中zz
The FizzBuzz problem is a classic test given in coding interviews. The task is simple:
FizzBu??zz問題是編碼面試中的經典測試。 任務很簡單:
Print integers 1 to N, but print “Fizz” if an integer is divisible by 3, “Buzz” if an integer is divisible by 5, and “FizzBuzz” if an integer is divisible by both 3 and 5.
打印從1到N的整數,如果將整數除以3,則打印“ Fizz”;如果將整數除以5,則打印“ Buzz”;如果將整數3和5均除,則打印“ FizzBu??zz”。
There are many ways to achieve the desired output, but some methods are better than others. Great solutions to FizzBuzz don’t “just work”. They adhere to good programming principles, allow flexibility for later changes, and play to a language’s strengths. With these things in mind, solving FizzBuzz is a great exercise for learning the specifics of a language and generally improving your programming.
有多種方法可以實現所需的輸出,但是有些方法比其他方法更好。 FizzBu??zz的出色解決方案“不可行”。 他們遵循良好的編程原則,可以靈活地進行以后的更改,并發揮語言的優勢。 考慮到這些問題,解決FizzBu??zz是學習語言細節并總體上改善編程的絕佳練習。
Below, I’ve explained five approaches to the FizzBuzz problem using R. Understanding each one will help to reinforce good coding practices and the use of R’s unique features. It might even help you get hired.
下面,我解釋了使用R解決FizzBu??zz問題的五種方法。了解每種方法將有助于加強良好的編碼習慣和R的獨特功能。 它甚至可以幫助您被錄用。
Note: although I explain all the code in this article, I assume a basic knowledge of fundamental programming principles and R data structures.
注意:盡管我解釋了本文中的所有代碼,但我假設您具有基本的編程原理和R數據結構的基本知識。
1.天真的解決方案 (1. A Naive Solution)
The most obvious way of solving FizzBuzz is to loop through a set of integers. In this loop, we use conditional statements to check whether each integer is divisible by 3 and/or 5.
解決FizzBu??zz的最明顯方法是遍歷一組整數。 在此循環中,我們使用條件語句檢查每個整數是否可被3和/或5整除。
The code above takes this approach. First, we store integers 1–50 in the vector fbnums. An empty vector named output is also defined to store the results of the procedure. Then, we check whether each integer in fbnums is evenly divisible by 3 and/or 5 using conditional statements within a for loop. These statements use the modulo operator %%, which returns the remainder of a division operation. As an example, the expression if (i %% 3 == 0) means “if we divide this integer by 3, is the remainder zero?”.
上面的代碼采用了這種方法。 首先,我們將1–50的整數存儲在向量fbnums 。 還定義了一個名為output的空向量來存儲過程的結果。 然后,我們使用for循環中的條件語句檢查fbnums中的每個整數是否可以被3和/或5均分。 這些語句使用模運算符%% ,該運算符返回除法運算的余數。 例如,表達式if (i %% 3 == 0)表示“如果將這個整數除以3,則余數為零嗎?”。
When one of the conditional statements returns true, the appropriate response is stored in the ith index of the output vector. Once the loop has completed, we print output to display the results of the process.
當條件語句之一返回true時,適當的響應將存儲在output向量的第i個索引中。 循環完成后,我們將打印output以顯示過程結果。
FizzBuzz for integers 1–50, printed as a vector.FizzBu??zz,整數1–50,打印為矢量。While this code works, it has several limitations:
盡管此代碼有效,但它有幾個限制:
- It uses a lot of messy conditional statements, which are hard to maintain. 它使用了很多混亂的條件語句,很難維護。
The statements i %% 3 == 0 and i %% 5 == 0 are repeated twice, making the code less efficient and more verbose.
語句i %% 3 == 0和i %% 5 == 0重復兩次,使代碼效率降低且更加冗長。
- The for loop is relatively slow and inefficient in R, especially with many iterations. for循環在R中相對較慢且效率低下,尤其是在許多迭代中。
Luckily, there are a few ways to improve upon this starting point.
幸運的是,有一些方法可以改善這個起點。
2.使用For循環的更好解決方案 (2. A Better Solution Using a For Loop)
It’s possible to reduce the number of conditional statements in our for loop, as shown below. This was inspired by an example by Tom Scott from his video on the FizzBuzz problem, which I’d highly recommend watching.
可以減少for循環中條件語句的數量,如下所示。 靈感來自湯姆·斯科特(Tom Scott)的有關FizzBu??zz問題的視頻中的一個例子,我強烈建議您觀看。
Here, fbnums and output are defined as they were before. But in the for loop, things work a little differently. First, we define the ith index in our output vector as a blank string. We then check whether our integer is divisible by 3 as in the last example. If this returns true, we paste “Fizz” onto the end of the blank string in output[i]. The equivalent statement for 5 and “Buzz” is evaluated in the next line. Finally, we check whether output[i] is empty. If so, we store the integer in this element to avoid returning a blank string. Once the loop is over, printing output gives the same result as the previous example.
在這里, fbnums和output的定義與以前一樣。 但是在for循環中,工作原理有所不同。 首先,我們將output向量中的第i個索引定義為空白字符串。 然后,如上例所示,檢查整數是否可被3整除。 如果返回true,則將“ Fizz”粘貼到output[i]空白字符串的末尾。 下一行將評估5和“嗡嗡聲”的等效語句。 最后,我們檢查output[i]是否為空。 如果是這樣,我們將整數存儲在此元素中,以避免返回空字符串。 循環結束后,打印output將得到與前面示例相同的結果。
This implementation is better than the previous for several reasons:
由于以下幾個原因,該實現比以前的實現更好:
- Pasting “Fizz” and “Buzz” onto a blank string like this eliminates the need for a statement evaluating “FizzBuzz”. This gets rid of repetition and looks neater. 像這樣將“ Fizz”和“ Buzz”粘貼到空白字符串上,就無需使用評估“ FizzBu??zz”的語句。 這樣可以避免重復,看起來更整潔。
- The format makes adding extra conditions?trivial, while keeping the code readable. 該格式使得添加額外條件變得微不足道,同時保持代碼可讀性。
This is good progress, but the use of a for loop still doesn’t leverage some of R’s unique features. The next three examples take full advantage of these and are great for picking up some advanced R techniques.
這是一個很好的進步,但是for循環的使用仍然沒有利用R的某些獨特功能。 接下來的三個示例充分利用了這些優點,非常適合采用一些高級R技術。
3.使用FizzBu??zzR的打包解決方案 (3. A Package Solution Using FizzBuzzR)
One of R’s strengths is its variety of user-friendly packages. FizzBuzzR is one of these and contains a single function meant for tackling the FizzBuzz problem. Calling fizzbuzz allows the user to specify the range of integers to evaluate, the interval by which to step through these integers, and the divisors for “Fizz” and “Buzz”. The output is then printed line by line in the console.
R的強項之一是其各種易于使用的軟件包。 FizzBu??zzR是其中之一,并且包含用于解決FizzBu??zz問題的單個功能。 調用fizzbuzz允許用戶指定要評估的整數范圍,逐步遍歷這些整數的時間間隔以及“ Fizz”和“ Buzz”的除數。 然后在控制臺中逐行打印輸出。
This implementation has the obvious advantage of being incredibly concise. But there’s a tradeoff: limited options for customisation. Let’s say an interviewer asks you to replace “Fizz” with “Biff”, or to store the output straight to a list. In these cases, you’d have to think of a completely new approach to do these things.
此實現的明顯優勢是非常簡潔。 但是需要權衡:定制的選項有限。 假設一位面試官要求您將“ Fizz”替換為“ Biff”,或將輸出直接存儲到列表中。 在這些情況下,您必須考慮一種全新的方法來執行這些操作。
4.使用map()的功能解決方案 (4. A Functional Solution Using map())
Rather than using a pre-written function, we can write our own FizzBuzz function and then apply this to each integer we want to evaluate.
無需使用預先編寫的函數,我們可以編寫自己的FizzBu??zz函數,然后將其應用于我們要求值的每個整數。
In the code above, we create a function called fbmap that evaluates a given integer according to our FizzBuzz rules. Our function does this using the same conditional statements as in Example 2. This time around, however, we replace certain values with arguments that we can pass into the function. Our divisors, 3 and 5, are replaced with the arguments mod1 and mod2, and our print statements “Fizz” and “Buzz” are replaced with exp1 and exp2. This means that when we call the function, we can define these values as whatever we like without having to rewrite lots of code.
在上面的代碼中,我們創建了一個名為fbmap的函數,該函數根據FizzBu??zz規則計算給定的整數。 我們的函數使用與示例2中相同的條件語句來執行此操作。但是,這次,我們將某些值替換為可以傳遞給函數的參數。 我們的除數3和5被替換為參數mod1和mod2 ,而我們的打印語句“ Fizz”和“ Buzz”被替換為exp1和exp2 。 這意味著當我們調用函數時,我們可以將這些值定義為任意值,而無需重寫大量代碼。
To get our output, we apply our function to each element of the fbnums vector using map_chr. To do this, we use the expression ~ fbmap(.x, 3, 5, "Fizz", "Buzz") inside map_chr . This tells fbmap to evaluate each element of the fbnums vector (denoted as .x ) with the divisors 3 and 5, and responses “Fizz” and “Buzz”. The results of these successive function calls are stored as separate elements in output, a character vector. Printing output then displays the correct results in the console.
為了獲得輸出,我們使用map_chr將函數應用于fbnums向量的每個元素。 要做到這一點,我們使用表達式~ fbmap(.x, 3, 5, "Fizz", "Buzz")內map_chr 。 這告訴fbmap用除數3和5評估fbnums向量的每個元素(表示為.x ),并響應“ Fizz”和“ Buzz”。 這些連續函數調用的結果作為單獨的元素存儲在output (字符向量)中。 打印output然后在控制臺中顯示正確的結果。
This implementation is great for a few reasons:
此實現之所以出色,有幾個原因:
- It’s clear, concise, and avoids repetition. 清晰,簡潔,避免重復。
Specifying arguments to fbmap provides flexibility. New conditions can also be added without complicating the codebase too much.
為fbmap指定參數提供了靈活性。 也可以添加新條件,而不會使代碼庫過于復雜。
It uses map_chr to apply a function across a vector, which is more efficient than using a for loop in R.
它使用map_chr在向量上應用函數,這比在R中使用for循環更有效。
To me, this is a fairly strong FizzBuzz solution. It looks good, makes the most of R, and isn’t any longer than the naive implementation in my first example. But what if you’d like your FizzBuzz solution to be optimally compatible with a tidyverse workflow?
對我來說,這是一個相當強大的FizzBu??zz解決方案。 它看起來不錯,可以充分利用R,而且僅比我第一個示例中的幼稚實現長。 但是,如果您希望FizzBu??zz解決方案與tidyverse工作流程最佳兼容,該怎么辦?
5.使用case_when()的矢量化解決方案 (5. A Vectorised Solution Using case_when())
For most tasks in R, there’s a pre-defined tidyverse function that’ll help you out. Want to apply some if statements to elements of a vector? Use case_when from the dplyr package.
對于R中的大多數任務,都有一個預定義的dydyverse函數可以幫助您。 是否要對向量元素應用某些if語句? 從dplyr軟件包中使用case_when 。
The code above is modified from an example in the case_when documentation, written by Hadley Wickham. Simply put, case_when applies if statements across a vector and returns an output based on the result of these statements. This example also makes sure to return the integer in question when it isn’t evenly divisible, with the expression TRUE ~ as.character(fbnums). Minus some different syntax, this is exactly what we’ve been doing in the previous examples. The difference is that case_when makes full use of R’s vectorisation capabilities, making it more efficient than the for loops in Solutions 1 and 2.
上面的代碼是根據Hadley Wickham編寫的case_when文檔中的示例修改的。 簡而言之, case_when適用于跨向量的if語句,并根據這些語句的結果返回輸出。 此示例還確保在整數不能被整除時返回該整數,其表達式為TRUE ~ as.character(fbnums) 。 減去一些不同的語法,這正是我們在先前示例中所做的。 區別在于case_when充分利用了R的向量化功能,使其比解決方案1和2中的for循環更有效。
On top of this, we still don’t repeat any conditional statements. Although we evaluate “FizzBuzz” as a separate condition, we can use simple maths to deduce that any instance of “FizzBuzz” is evenly divisible by 15, the lowest common factor of 3 and 5. This avoids the need for repeating statements containing %% 3 == 0 and %% 5 == 0. Further, the code is still easy to read and add to if required. This could be achieved by adding more conditions to case_when, or piping to another function after case_when to fulfil more complicated requirements. All in all, case_when is a great function for solving the FizzBuzz problem in R.
最重要的是,我們仍然不重復任何條件語句。 盡管我們將“ FizzBu??zz”作為一個單獨的條件進行評估,但我們可以使用簡單的數學來推斷“ FizzBu??zz”的任何實例均可以被15整除,最小公因子3和5。這避免了重復包含%% 3 == 0語句的需要。 %% 3 == 0和%% 5 == 0 。 此外,該代碼仍然易于閱讀,并在需要時添加。 這可以通過在case_when添加更多條件或在case_when之后case_when管道傳遞到另一個函數來滿足更復雜的要求來實現。 總而言之, case_when是解決R中的FizzBu??zz問題的強大功能。
結論 (Conclusion)
Solving the FizzBuzz problem demonstrates the value of learning to write neat code. While every solution above works, some are far easier to maintain in a large real-life codebase. Why are these implimentations better? They adhere to good programming principles, and make the most of R’s capabilities.
解決FizzBu??zz問題證明了學習編寫簡潔代碼的價值。 盡管上述每種解決方案都可以使用,但是在大型現實代碼庫中維護起來卻容易得多 。 為什么這些內含更好? 他們遵循良好的編程原則,并充分利用R的功能。
So the next time you code something, interview task or otherwise, ask yourself a few things. Am I repeating myself? How can I play to the strengths of my chosen language? Is the code I’m writing easy to maintain? Answering these questions won’t just help you write a good FizzBuzz solution. They’ll make you a better programmer.
因此,下次您編寫代碼,進行面試或其他任務時,請問自己幾件事。 我在重復自己嗎? 我如何發揮自己選擇的語言的優勢? 我編寫的代碼易于維護嗎? 回答這些問題不僅可以幫助您編寫出色的FizzBu??zz解決方案。 它們將使您成為更好的程序員。
翻譯自: https://towardsdatascience.com/how-to-solve-the-fizzbuzz-problem-in-r-c62e7e6c959a
deepin中zz
總結
以上是生活随笔為你收集整理的deepin中zz_如何解决R中的FizzBuzz问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 稀疏组套索_Python中的稀疏组套索
- 下一篇: 小米8ud版和普通版有什么不同?(我的小