Maison > développement back-end > Tutoriel Python > 在简化代码时最有优势的是 Python 吗?

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

WBOY
Libérer: 2016-06-06 16:23:22
original
1167 Les gens l'ont consulté

如打印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>
Copier après la connexion

回复内容:

不是

J

<code class="language-text">+/ (#~ (0=2&|) *. (0=3&|)) 1+i.100
</code>
Copier après la connexion
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>
Copier après la connexion
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>
Copier après la connexion
可以被2和3整除,不就是被6整除嘛
sum [6,12..101] Ruby 也好简单
<code class="language-text">(1..100).select{|x| x%6 == 0 }.inject(:+)
</code>
Copier après la connexion
这种东西就是比语法糖和标准库,比出来也是意义不大。。。 sum [6,12..100]


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

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


还有那些把[1..100]写成[0..101]的那些泥们垢了!有审过题么,就答?知乎都这样了还怎么玩耍...
Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal