Last active
August 29, 2015 13:56
-
-
Save SaveTheRbtz/9184769 to your computer and use it in GitHub Desktop.
python factorials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import imap | |
fact_eval1 = lambda n: eval("*".join(imap(str, xrange(1, n + 1)))) if n > 1 else 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import imap, islice, count, takewhile, repeat | |
from operator import mul | |
def chunks(it, n): | |
return takewhile(bool, | |
(tuple(islice(start, n)) | |
for start in repeat(iter(it)))) | |
def fact_eval2(n): | |
assert n >= 0, "fact_eval2 supports only factorials for number >= 0" | |
if n in (0, 1): | |
return 1 | |
return reduce(mul, imap(eval, | |
("*".join(imap(str, batch)) for batch in | |
chunks(islice(count(1), n), 10000)))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* cc -shared -olibfact_eval4.so fact_eval4.c */ | |
unsigned long long | |
fact(unsigned long long n) | |
{ | |
register unsigned long long result; | |
if (n == 0) { | |
return 1; | |
} | |
/* TODO: overflow check */ | |
for (result = n; n > 1; result *= n - 1, --n) /* NOT USED */; | |
return result; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ctypes | |
c_ext = ctypes.cdll.LoadLibrary('./libfact_eval4.so') | |
c_fact = c_ext.fact | |
c_fact.argtypes = (ctypes.c_ulonglong, ) | |
c_fact.restype = ctypes.c_ulonglong | |
def fact_eval4(n): | |
return c_fact(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment