這就是問題
完成回傳長度為 n 的陣列的函式,從給定的數字 x 和前一個數字的平方開始。如果 n 為負數或零,則回傳一個空陣列/串列。
Examples
2, 5 --> [2, 4, 16, 256, 65536]
3, 3 --> [3, 9, 81]
對于我一直在學習的東西來說似乎很容易。
在完成示例時,我已經完成了大部分代碼:
def squares(x, n)
array = [x]
i = 1
while i < n
array << x *= x
i = 1
end
return array
end
PASS Test.assert_equals(squares(2,5),[2,4,16,256,65536]);
PASS Test.assert_equals(squares(3,3),[3,9,81]);
PASS Test.assert_equals(squares(5,3),[5,25,625]);
PASS Test.assert_equals(squares(10,4),[10,100,10000,100000000]);
我遇到的問題是,問題還要求n是一個正整數,如果不是,則回傳一個空陣列:
如果n為負數或零,則回傳一個空陣列/串列。
我很難弄清楚如何正確地解決這個問題。我嘗試了幾種不同的方法,但都沒有成功。這是我認為自己走在正確軌道上的嘗試之一:
def squares(x, n)
array = [x]
arr = []
i = 1
if n < 0
return arr
elsif i < n
array << x *= x
end
i = 1
end
end
uj5u.com熱心網友回復:
一種方法是創建一個列舉器,然后獲取所需數量的元素:
def squares(x, m)
Enumerator.produce(x) { |n| n*n }.take(m)
end
squares(2, 5)
#=> [2, 4, 16, 256, 65536]
squares(3, 5)
#=> [3, 9, 81, 6561, 43046721]
請參閱Enumerator::produce。
uj5u.com熱心網友回復:
只需在方法頂部添加以下行即可解決它:
return [] if n <= 0
盡管還有許多其他方法可以做到這一點。例如:
def squares(x, n)
a = x
(1..n).map { |e| a.tap { a *= a } }
end
這依賴于這樣一個事實,即 Ruby 范圍的 formm..n不產生任何元素 if n <= m。
uj5u.com熱心網友回復:
首先,我想說這個問題很愚蠢。不是你的問題,我說的是問題陳述:
完成回傳長度為 n 的陣列的函式,從給定的數字 x 和前一個數字的平方開始。如果 n 為負數或零,則回傳一個空陣列/串列。
它有幾個問題。
- 它要求您回傳一個
Array. 在編程中,您應該始終努力使您的回傳值盡可能通用,以便您的子例程可以在盡可能多的不同背景關系中重用。如果您的子例程回傳一個Array并且n非常大,那么Array將使用大量記憶體。但是,例如,如果有人只想遍歷所有這些值,則不需要Array. 回傳通常稱為流或 Ruby 稱為Enumerator. 如果客戶真的Enumerator需要.ArrayArray - 這同樣適用于回傳預定數量的元素的要求
n。回傳無限數量的元素并讓客戶選擇他們需要的數量會更有意義。例如,如果他們不知道元素的數量怎么辦?如果他們想將這些數字相加直到達到某個閾值怎么辦?根據問題陳述的要求,他們必須猜測需要多少數字才能達到該閾值,而如果您給他們一個無限流,他們可以迭代流,直到找到答案。 - 這是我最討厭的問題之一:問題陳述談到了函式,但 Ruby 沒有函式。它有方法。這是兩個不同的東西。
- 它還將陣列和串列視為同一事物。他們不是。
- [我會把這個放在括號里,因為它可以用任何一種方式來爭論。
raise我認為對a來說更有意義Exception,更準確地說,ArgumentError對于負數n而不是回傳一個空結果。空結果對 有意義n == 0,但不一定對負數n。]
因此,簡而言之,問題陳述的措辭促進了糟糕的 Ruby 術語(函式、串列)和糟糕的編程實踐(太具體的回傳值,沒有正確地發出錯誤信號)。
無論如何,回到你的問題。
我遇到的問題是,問題還要求 n 是一個正整數,如果不是,則回傳一個空陣列:
如果n為負數或零,則回傳一個空陣列/串列。
正如其他一些答案中所提到的,您幾乎可以將該陳述句翻譯成 Ruby 代碼:
# "If n is negative":
if n.negative?
# " …or zero":
if n.negative? || n.zero?
# "… return an empty array":
if n.negative? || n.zero? then return [] end
現在我們可以稍微優化一下。首先,如果你有一個沒有else分支且分支中只有一個運算式的條件運算式then,你可以使用所謂的修飾符形式:
return [] if n.negative? || n.zero?
其次,“負數或零”只是“非正數”的另一種說法,這使我們可以簡化條件:
return [] if !n.positive?
我們可以通過使用條件運算式的反轉形式來使其更具可讀性unless:
return [] unless n.positive?
這滿足了問題陳述中的要求,但是,正如我所提到的,我個人認為傳遞負長度應該是一個錯誤,所以我可能寧愿寫這樣的東西:
raise ArgumentError, "length must not be negative but you passed `#{n}`" if n.negative?
return [] if n.zero?
As I mentioned above, though, the way the problem statement forces you to write the code is not how you would actually write it in the real world. In the real world, you would decompose the problem into various orthogonal components, and make sure that each of those components can also be used separately.
The reason is that "a sequence of squares of a specific length" is a very specific problem, which it makes it very unlikely that someone else is going to have the exact same problem, and thus makes it unlikely that your code can be re-used.
I would decompose this problem into at least these subproblems:
- Produce an infinite stream given a subroutine to produce the next element.
- Take a specified number of elements from an infinite stream.
- Square a number.
If you have solved these three subproblems, you can solve the specific problem using the solutions by (1) producing an infinite stream of (3) squares and (2) taking only the first n elements.
What are the advantages of this approach? I see two major ones:
- You have broken the problem down into simpler subproblems: each of those three subproblems is simpler than the original problem. Therefore, each of the three problems is easier to solve than the original one. Once you have solved the three subproblems, the original problem also becomes easy to solve because you just have to plug the three subproblems together.
- You have built a library of three general solutions that are useful beyond the original problem. You can use these to solve other problems as well.
In fact, I have hidden the most important benefit from you: remember how I said multiple times that making the problem more general helps make the solution more reusable, so that the solution becomes useful in more contexts? Well, it turns out that #1 and #2 are so general and so useful in so many contexts, that they have already been written for us! The solutions to #1 and #2 are part of the Ruby core library, so we don't even need to write them ourselves.
You can produce an infinite Enumerator using the method Enumerator::produce, which is Ruby's name for an unfold aka Anamorphism. And you can take a specified number of elements from an Enumerable using Enumerable#take. So, all that's left for us to solve here is how to square a number, which is trivial.
You will also note that Enumerable#take returns an empty Array when you pass 0 as the number of elements and raises an ArgumentError when you pass a negative number, so by decomposing our problem and delegating the solution of sub-problem #2 to Enumerable#take we also get the error and edge case behavior we want for free.
You can already see in Cary Swoveland's answer what the resulting code looks like, so I will not repeat it here. Rather, I want to show what I meant at the very beginning when I said that returning an infinite stream of squares would be more useful because the client could then apply their own criterion for how many elements to take. Remember the problem I posed:
What if they want to sum those numbers until they reach a certain threshold? With the requirement from the problem statement, they would have to guess how many numbers they need in order to reach that threshold, whereas if you give them an infinite stream, they can just iterate the stream until they have found their answer.
If we write our method like this:
def infinite_stream_of_squares_starting_with(initial_value)
Enumerator.produce(initial_value) { _1 * _1 }
end
Then all the client has to do is to replace Enumerable#take (which allows them to take a specific number of elements) with Enumerable#take_while (which allows them to take elements while a specific condition is met), and they can write:
def squares_until_sum_reaches_threshold(initial_value, threshold)
sum = 0
infinite_stream_of_squares_starting_with(initial_value).
take_while { (sum = _1) < threshold }
end
So, in summary, it is always a good idea to break down problems into subproblems and generalize those subproblems, because breaking the problem down makes it simpler, and generalizing makes it both more likely to be useful in other contexts, and more likely to already have been solved by someone else. In particular, you should always separate I/O from computation, and try to separate generating data, transforming data, filtering data, and reducing data from each other.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447467.html
