- 论坛徽章:
- 0
|
原帖由 starfuck 于 2008-12-3 19:01 发表
移来移去取1000000个早死了,别说求n!了
我们来比较一下:
你的代码,不带输出的,公平吧?
- def factorial(n):
- return reduce(lambda x, y: x*y, xrange(1, n+1), 1)
-
- def nth_permutation(elements, n):
- for i in reversed(xrange(len(elements))):
- x, n = divmod(n, factorial(i))
- yield elements.pop(x)
-
- list(nth_permutation(range(1000), 0))
复制代码
- zxl@VIKI:~/src$ time python 1.py
- real 0m1.198s
- user 0m1.064s
- sys 0m0.024s
复制代码
注意你这里是1000 个数的排列,取第 0 个。如果是 10000 个数,我这里等了一分钟没出来。
我的代码:
- fun upto 0 = []
- | upto n = n:: upto (n-1)
-
- fun nextperm (x::xs) =
- let fun next (r::rs, y::ys) =
- if r<=y then next(y::r::rs, ys)
- else let fun swap [x] = y::x::ys
- | swap (x1::x2::xs) =
- if y<x2 then x1::swap (x2::xs)
- else (y::x2::xs)@(x1::ys)
- in swap (r::rs) end
- | next (r, []) = r
- in next ([x], xs) end;
-
- val x = upto 10000;
-
- fun repeat 1 = nextperm
- | repeat n = nextperm o repeat (n-1);
-
- (repeat 10000) x;
- quit();
复制代码
一万个数的排列,取第一万零一个,带部分输出的。
- time mosml 1.sml
- real 0m0.113s
- user 0m0.056s
- sys 0m0.016s
复制代码 |
|