Heim  >  Artikel  >  Backend-Entwicklung  >  在简化代码时最有优势的是 Python 吗?

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

WBOY
WBOYOriginal
2016-06-06 16:23:221149Durchsuche

如打印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]的那些泥们垢了!有审过题么,就答?知乎都这样了还怎么玩耍...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn