366 points · by r11t · 16y ago · 90 comments
import urllib
import json
def fact(n):
res = urllib.urlopen('http://math.org/factorial/?' +
urllib.urlencode({'n':n, 'format':'json'})).read()
return json.loads(res)['answer']
fact(6)
Edit: for a "web scale systems guy" throw an @memcache_memoize in there :)Edit2: fixed a syntax error.
Edit3: general cased it. thanks lolcraft!
{'n':6, 'format':'json'}
Shouldn't that be: {'n':n, 'format':'json'} # "close enough" programmer
import math
def fact(x):
math.sqrt(2*math.pi*n) * math.pow(n/math.e, n)
print fact(6)
# lazy-er programmer
def fact(x):
factorials = {6:720} # found on my calculator, add more as they come up
if factorials.has_key(x):
return factorials[x]
else:
raise NotImplementedError
print fact(6)http://www.hackerne.ws/item?id=1012877
Wow the domain can make a huge difference. :)
whois ycombinator.com -> pg
whois hackerne.ws -> some godaddy registrar.
...They took us jobs!
I'm not sure what it is, but at some point every pythonista seems to go through this love affair with functools + itertols + roll your own haskellish modules.
For example: I once rolled my own lisp style immutable list type using nested tuples, i.e. (1,(2,(3,None))) for a problem that they were particularly well suited. (http://en.wikipedia.org/wiki/Knapsack_problem#0-1_knapsack_p...) and got about a 10% speedup. In the end though I threw it out because it was far too ugly.
But I always prefer a def and a map to a for loop.
For those I either go with a list comprehension or a generator expression.
def factorial(x):
return x * factorial(x-1) if x > 1 else 1http://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer....
And here is one that is actually well done for Haskell.
class FactorialCommand(object):
def set_num(self, num):
self.__num = num
def get_num(self):
return self.__num
def execute(self):
result = 1
i = 2
while i <= self.get_num():
result = result * i
i = i + 1
return result
cmd = FactorialCommand()
cmd.set_num(6)
print cmd.execute() def fact(n):
return eval('*'.join([str(x+1) for x in xrange(n)] + ['1'])) f= lambda n: [[[j for j in (j*i,)][0] for i in range(2,n+1)][-1] for j in (1,)][0] reduce(lambda x, y: x * y, range(1, 100))
Replicating that in C is certainly possible but you're probably not going to do it quickly, unless you're already pretty deep into that sort of thing. def fact(l):
return sum(map(bool,reduce(lambda I,l:''.join([l for I in I]),
['+'+'+'*l for l in xrange(l)])))
assert fact(6)==720 (*$:@:<:)^:(1&<) 6
Finds the factorial recursively. J programmers are masochists.(From: http://rosettacode.org/wiki/Factorial_function#Recursive_11)
from math import factorial
done.(defn factorial [n] (reduce * (range 1 (inc n))))
;; Any programmer reading HN long enough to experiment with some lisp / clojure ;)
(defn factorial [n]
(apply * (range 1 (+ n 1)))) fact = init_fact()
...
res = fact[x]for all the closet functional programmers around here :)