在简化代码时最有优势的是 Python 吗?

WBOY
發布: 2016-06-06 16:23:22
原創
1158 人瀏覽過

如打印1-100中可被2和3整除的總和
最一般的情況可能这样写

<span class="n">TheSum</span><span class="o">=</span><span class="mi">0</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="mi">101</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">x</span> <span class="o">%</span><span class="mi">2</span><span class="o">==</span><span class="mi">0</span> <span class="ow">and</span> <span class="n">x</span><span class="o">%</span><span class="mi">3</span><span class="o">==</span><span class="mi">0</span><span class="p">:</span>
        <span class="n">TheSum</span><span class="o">+=</span><span class="n">x</span>
<span class="k">print</span> <span class="n">TheSum</span>
登入後複製

回复内容:

不是

J

<code class="language-text">+/ (#~ (0=2&|) *. (0=3&|)) 1+i.100
</code>
登入後複製
Scala:
6 to 100 by 6 sum
不妨考虑一下可读性吧 sum(range(6,101,6))
<code class="language-text">1 to(100) asList select(%6==0) sum
</code>
登入後複製
Haskell :sum [x | x
<code class="language-haskell"><span class="nf">sum</span> <span class="p">[</span><span class="n">x</span> <span class="o">|</span> <span class="n">x</span> <span class="ow"> <span class="p">[</span><span class="mi">1</span><span class="o">..</span><span class="mi">101</span><span class="p">],</span> <span class="n">x</span> <span class="p">`</span><span class="n">mod</span><span class="p">`</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">&&</span> <span class="n">x</span> <span class="p">`</span><span class="n">mod</span><span class="p">`</span> <span class="mi">3</span> <span class="o">==</span> <span class="mi">0</span><span class="p">]</span>
</span></code>
登入後複製
可以被2和3整除,不就是被6整除嘛
sum [6,12..101] Ruby 也好简单
<code class="language-text">(1..100).select{|x| x%6 == 0 }.inject(:+)
</code>
登入後複製
这种东西就是比语法糖和标准库,比出来也是意义不大。。。 sum [6,12..100]


旁边那些好意思说自己写的是Haskell么…好歹也写成下面这样吧…

sum . filter ((==0).('mod' 6)) $ [1..100]


还有那些把[1..100]写成[0..101]的那些泥们垢了!有审过题么,就答?知乎都这样了还怎么玩耍...
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板