Home > Article > Backend Development > 在简化代码时最有优势的是 Python 吗?
如打印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>
<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整除嘛<code class="language-text">(1..100).select{|x| x%6 == 0 }.inject(:+)
</code>
这种东西就是比语法糖和标准库,比出来也是意义不大。。。
sum [6,12..100]