Skip to content

Instantly share code, notes, and snippets.

@hxer
Created March 1, 2016 01:58
Show Gist options
  • Save hxer/710e90e9a0ff08d65843 to your computer and use it in GitHub Desktop.
Save hxer/710e90e9a0ff08d65843 to your computer and use it in GitHub Desktop.
python factorial
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
by hx, 2015.11.24
version:python2.7.x
"""
def factorial(x):
res = 1
for i in xrange(2, x+1):
res *= i
return res
def fact_1(x):
return x>1 and x*fact_1(x-1) or 1
def fact_2(x):
f = lambda x: x>1 and x*f(x-1) or 1
return f(x)
#@tailcall #NameError: name 'tailcall' is not defined
def fact_3(x, acc=1):
if x:
return fact_3(x.__sub__(1), acc.__mul__(x))
else:
return acc
def fact_4(x):
import math
return math.factorial(x)
if __name__ == "__main__":
import sys
print(factorial(6))
print(fact_1(6))
print(fact_2(6))
print(fact_3(6))
print(fact_4(6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment