各種程序員所寫的階乘算法代碼
# -*- coding: utf-8 -*-
#新手程序員(遞歸)
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x - 1)
PRint factorial(6)
#有一年 Python 經(jīng)驗(yàn)的程序員
def Factorial(x):
res = 1
for i in xrange(2, x + 1):
res *= i
return res
print Factorial(6)
#懶惰的 Python 程序員
def fact(x):
return x > 1 and x * fact(x - 1) or 1
print fact(6)
#更懶惰的 Python 程序員
f = lambda x: x and x * f(x - 1) or 1
print f(6)
#專家級(jí) Python 程序員
import Operator as op
import functional as f
fact = lambda x: f.foldl(op.mul, 1, xrange(2, x + 1))
print fact(6)
#Python 黑客
import sys
def fact(x, acc = 1):
if x: return fact(x.__sub__(1), acc.mul__(x))
return acc
sys.stdout.write(str(fact(6)) + '/n')
#專家級(jí)程序員
imort c_math
fact = c_math.fact
print fact(6)
#有一年 C 經(jīng)驗(yàn)的程序員
def fact(x):
result = i = 1;
while (i <= x):
result *= i;
i += 1;
return result;
print(fact(6))
本人是一名 Python 新手 ,在網(wǎng)上看到這篇文章覺得很有趣, 所以想在博客園重寫一遍。
一方面提升下自己的 Python水平 , 另一方面也可以與更多的 Python 愛好者 學(xué)習(xí) 分享。
人生苦短 我用Python QAQ
這里是更為完整的原文地址: http://python.jobbole.com/15005/
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注