deepin中zz_如何解决R中的FizzBuzz问题
deepin中zz
The FizzBuzz problem is a classic test given in coding interviews. The task is simple:
FizzBu??zz問(wèn)題是編碼面試中的經(jīng)典測(cè)試。 任務(wù)很簡(jiǎn)單:
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的整數(shù),如果將整數(shù)除以3,則打印“ Fizz”;如果將整數(shù)除以5,則打印“ Buzz”;如果將整數(shù)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.
有多種方法可以實(shí)現(xiàn)所需的輸出,但是有些方法比其他方法更好。 FizzBu??zz的出色解決方案“不可行”。 他們遵循良好的編程原則,可以靈活地進(jìn)行以后的更改,并發(fā)揮語(yǔ)言的優(yōu)勢(shì)。 考慮到這些問(wèn)題,解決FizzBu??zz是學(xué)習(xí)語(yǔ)言細(xì)節(jié)并總體上改善編程的絕佳練習(xí)。
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問(wèn)題的五種方法。了解每種方法將有助于加強(qiáng)良好的編碼習(xí)慣和R的獨(dú)特功能。 它甚至可以幫助您被錄用。
Note: although I explain all the code in this article, I assume a basic knowledge of fundamental programming principles and R data structures.
注意:盡管我解釋了本文中的所有代碼,但我假設(shè)您具有基本的編程原理和R數(shù)據(jù)結(jié)構(gòu)的基本知識(shí)。
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的最明顯方法是遍歷一組整數(shù)。 在此循環(huán)中,我們使用條件語(yǔ)句檢查每個(gè)整數(shù)是否可被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的整數(shù)存儲(chǔ)在向量fbnums 。 還定義了一個(gè)名為output的空向量來(lái)存儲(chǔ)過(guò)程的結(jié)果。 然后,我們使用for循環(huán)中的條件語(yǔ)句檢查fbnums中的每個(gè)整數(shù)是否可以被3和/或5均分。 這些語(yǔ)句使用模運(yùn)算符%% ,該運(yùn)算符返回除法運(yùn)算的余數(shù)。 例如,表達(dá)式if (i %% 3 == 0)表示“如果將這個(gè)整數(shù)除以3,則余數(shù)為零嗎?”。
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.
當(dāng)條件語(yǔ)句之一返回true時(shí),適當(dāng)?shù)捻憫?yīng)將存儲(chǔ)在output向量的第i個(gè)索引中。 循環(huán)完成后,我們將打印output以顯示過(guò)程結(jié)果。
FizzBuzz for integers 1–50, printed as a vector.FizzBu??zz,整數(shù)1–50,打印為矢量。While this code works, it has several limitations:
盡管此代碼有效,但它有幾個(gè)限制:
- It uses a lot of messy conditional statements, which are hard to maintain. 它使用了很多混亂的條件語(yǔ)句,很難維護(hù)。
The statements i %% 3 == 0 and i %% 5 == 0 are repeated twice, making the code less efficient and more verbose.
語(yǔ)句i %% 3 == 0和i %% 5 == 0重復(fù)兩次,使代碼效率降低且更加冗長(zhǎng)。
- The for loop is relatively slow and inefficient in R, especially with many iterations. for循環(huán)在R中相對(duì)較慢且效率低下,尤其是在許多迭代中。
Luckily, there are a few ways to improve upon this starting point.
幸運(yùn)的是,有一些方法可以改善這個(gè)起點(diǎn)。
2.使用For循環(huán)的更好解決方案 (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循環(huán)中條件語(yǔ)句的數(shù)量,如下所示。 靈感來(lái)自湯姆·斯科特(Tom Scott)的有關(guān)FizzBu??zz問(wèn)題的視頻中的一個(gè)例子,我強(qiáng)烈建議您觀看。
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循環(huán)中,工作原理有所不同。 首先,我們將output向量中的第i個(gè)索引定義為空白字符串。 然后,如上例所示,檢查整數(shù)是否可被3整除。 如果返回true,則將“ Fizz”粘貼到output[i]空白字符串的末尾。 下一行將評(píng)估5和“嗡嗡聲”的等效語(yǔ)句。 最后,我們檢查output[i]是否為空。 如果是這樣,我們將整數(shù)存儲(chǔ)在此元素中,以避免返回空字符串。 循環(huán)結(jié)束后,打印output將得到與前面示例相同的結(jié)果。
This implementation is better than the previous for several reasons:
由于以下幾個(gè)原因,該實(shí)現(xiàn)比以前的實(shí)現(xiàn)更好:
- 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”粘貼到空白字符串上,就無(wú)需使用評(píng)估“ FizzBu??zz”的語(yǔ)句。 這樣可以避免重復(fù),看起來(lái)更整潔。
- The format makes adding extra conditions?trivial, while keeping the code readable. 該格式使得添加額外條件變得微不足道,同時(shí)保持代碼可讀性。
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.
這是一個(gè)很好的進(jìn)步,但是for循環(huán)的使用仍然沒(méi)有利用R的某些獨(dú)特功能。 接下來(lái)的三個(gè)示例充分利用了這些優(yōu)點(diǎn),非常適合采用一些高級(jí)R技術(shù)。
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的強(qiáng)項(xiàng)之一是其各種易于使用的軟件包。 FizzBu??zzR是其中之一,并且包含用于解決FizzBu??zz問(wèn)題的單個(gè)功能。 調(diào)用fizzbuzz允許用戶(hù)指定要評(píng)估的整數(shù)范圍,逐步遍歷這些整數(shù)的時(shí)間間隔以及“ Fizz”和“ Buzz”的除數(shù)。 然后在控制臺(tái)中逐行打印輸出。
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.
此實(shí)現(xiàn)的明顯優(yōu)勢(shì)是非常簡(jiǎn)潔。 但是需要權(quán)衡:定制的選項(xiàng)有限。 假設(shè)一位面試官要求您將“ Fizz”替換為“ Biff”,或?qū)⑤敵鲋苯哟鎯?chǔ)到列表中。 在這些情況下,您必須考慮一種全新的方法來(lái)執(zhí)行這些操作。
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.
無(wú)需使用預(yù)先編寫(xiě)的函數(shù),我們可以編寫(xiě)自己的FizzBu??zz函數(shù),然后將其應(yīng)用于我們要求值的每個(gè)整數(shù)。
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.
在上面的代碼中,我們創(chuàng)建了一個(gè)名為fbmap的函數(shù),該函數(shù)根據(jù)FizzBu??zz規(guī)則計(jì)算給定的整數(shù)。 我們的函數(shù)使用與示例2中相同的條件語(yǔ)句來(lái)執(zhí)行此操作。但是,這次,我們將某些值替換為可以傳遞給函數(shù)的參數(shù)。 我們的除數(shù)3和5被替換為參數(shù)mod1和mod2 ,而我們的打印語(yǔ)句“ Fizz”和“ Buzz”被替換為exp1和exp2 。 這意味著當(dāng)我們調(diào)用函數(shù)時(shí),我們可以將這些值定義為任意值,而無(wú)需重寫(xiě)大量代碼。
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將函數(shù)應(yīng)用于fbnums向量的每個(gè)元素。 要做到這一點(diǎn),我們使用表達(dá)式~ fbmap(.x, 3, 5, "Fizz", "Buzz")內(nèi)map_chr 。 這告訴fbmap用除數(shù)3和5評(píng)估fbnums向量的每個(gè)元素(表示為.x ),并響應(yīng)“ Fizz”和“ Buzz”。 這些連續(xù)函數(shù)調(diào)用的結(jié)果作為單獨(dú)的元素存儲(chǔ)在output (字符向量)中。 打印output然后在控制臺(tái)中顯示正確的結(jié)果。
This implementation is great for a few reasons:
此實(shí)現(xiàn)之所以出色,有幾個(gè)原因:
- It’s clear, concise, and avoids repetition. 清晰,簡(jiǎn)潔,避免重復(fù)。
Specifying arguments to fbmap provides flexibility. New conditions can also be added without complicating the codebase too much.
為fbmap指定參數(shù)提供了靈活性。 也可以添加新條件,而不會(huì)使代碼庫(kù)過(guò)于復(fù)雜。
It uses map_chr to apply a function across a vector, which is more efficient than using a for loop in R.
它使用map_chr在向量上應(yīng)用函數(shù),這比在R中使用for循環(huán)更有效。
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?
對(duì)我來(lái)說(shuō),這是一個(gè)相當(dāng)強(qiáng)大的FizzBu??zz解決方案。 它看起來(lái)不錯(cuò),可以充分利用R,而且僅比我第一個(gè)示例中的幼稚實(shí)現(xiàn)長(zhǎng)。 但是,如果您希望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.
對(duì)于R中的大多數(shù)任務(wù),都有一個(gè)預(yù)定義的dydyverse函數(shù)可以幫助您。 是否要對(duì)向量元素應(yīng)用某些if語(yǔ)句? 從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.
上面的代碼是根據(jù)Hadley Wickham編寫(xiě)的case_when文檔中的示例修改的。 簡(jiǎn)而言之, case_when適用于跨向量的if語(yǔ)句,并根據(jù)這些語(yǔ)句的結(jié)果返回輸出。 此示例還確保在整數(shù)不能被整除時(shí)返回該整數(shù),其表達(dá)式為T(mén)RUE ~ as.character(fbnums) 。 減去一些不同的語(yǔ)法,這正是我們?cè)谙惹笆纠兴龅摹?區(qū)別在于case_when充分利用了R的向量化功能,使其比解決方案1和2中的for循環(huán)更有效。
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.
最重要的是,我們?nèi)匀徊恢貜?fù)任何條件語(yǔ)句。 盡管我們將“ FizzBu??zz”作為一個(gè)單獨(dú)的條件進(jìn)行評(píng)估,但我們可以使用簡(jiǎn)單的數(shù)學(xué)來(lái)推斷“ FizzBu??zz”的任何實(shí)例均可以被15整除,最小公因子3和5。這避免了重復(fù)包含%% 3 == 0語(yǔ)句的需要。 %% 3 == 0和%% 5 == 0 。 此外,該代碼仍然易于閱讀,并在需要時(shí)添加。 這可以通過(guò)在case_when添加更多條件或在case_when之后case_when管道傳遞到另一個(gè)函數(shù)來(lái)滿(mǎn)足更復(fù)雜的要求來(lái)實(shí)現(xiàn)。 總而言之, case_when是解決R中的FizzBu??zz問(wèn)題的強(qiáng)大功能。
結(jié)論 (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問(wèn)題證明了學(xué)習(xí)編寫(xiě)簡(jiǎn)潔代碼的價(jià)值。 盡管上述每種解決方案都可以使用,但是在大型現(xiàn)實(shí)代碼庫(kù)中維護(hù)起來(lái)卻容易得多 。 為什么這些內(nèi)含更好? 他們遵循良好的編程原則,并充分利用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.
因此,下次您編寫(xiě)代碼,進(jìn)行面試或其他任務(wù)時(shí),請(qǐng)問(wèn)自己幾件事。 我在重復(fù)自己?jiǎn)?#xff1f; 我如何發(fā)揮自己選擇的語(yǔ)言的優(yōu)勢(shì)? 我編寫(xiě)的代碼易于維護(hù)嗎? 回答這些問(wèn)題不僅可以幫助您編寫(xiě)出色的FizzBu??zz解決方案。 它們將使您成為更好的程序員。
翻譯自: https://towardsdatascience.com/how-to-solve-the-fizzbuzz-problem-in-r-c62e7e6c959a
deepin中zz
總結(jié)
以上是生活随笔為你收集整理的deepin中zz_如何解决R中的FizzBuzz问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 稀疏组套索_Python中的稀疏组套索
- 下一篇: 图像生成对抗生成网络gan_GAN生成汽