Re: [問題] 1-9位數不重複印出來 (Python)

作者: SocketAM2 (AM2)   2016-12-08 18:49:38
挑戰最快的Python code (跟C比直接投降可以算輸一半嗎?)
在MBPR上輸入1~9都印一趟總共需約5.7秒
==========================================================
import time
def benchmark(function, args_set=[None], repeat=1):
total_time = 0
clock = time.clock
for i in xrange(repeat):
ret_set = []
for args in args_set:
start = clock()
ret = function(*args)
total_time += clock() - start
ret_set.append(ret)
print ret_set
print "average time : {t}".format(t=total_time/repeat)
def recursive_int(n):
free_digits = set(xrange(10))
def recurse_1():
if n == 1:
for i in xrange(1, 10):
yield i
else:
for i in xrange(1, 10):
free_digits.remove(i)
for next_level in recurse(i):
yield next_level
free_digits.add(i)
def recurse(tmp):
if n == 11 - len(free_digits):
for i in free_digits:
yield 10 * tmp + i
else:
for i in free_digits.copy():
free_digits.remove(i)
for next_level in recurse(10 * tmp + i):
yield next_level
free_digits.add(i)
ans = map(None, recurse_1())
print ans
return len(ans)
if __name__ == "__main__":
ALGO_TO_BE_TESTED = [
recursive_int,
# add other competitors here
]
ARGS_SET = [[n] for n in xrange(1, 10)]
REPEAT = 1
for function in ALGO_TO_BE_TESTED:
benchmark(function, ARGS_SET, REPEAT)
===============================================================
※ 引述《fourdollars (四元)》之銘言:
: 這是我目前找出來 Python 3 上面執行速度最快的方法
: 不過還是比 Perl 的版本要慢一點點,最快的還是 C 大概是 Perl 的十倍快
: #!/usr/bin/env python3
: import sys
: power = int(sys.argv[1])
: class Num(object):
: def __init__(self, power):
: self.upper = 10 ** power
: def __iter__(self):
: for i in range(1, self.upper):
: num = str(i)
: if len(set(num)) == len(num):
: yield(i)
: num = Num(power)
: numbers = [str(i) for i in num]
: print(', '.join(numbers))
: ※ 引述《mikemagic88 (Mikemagic88)》之銘言:
: : 使用者輸入1 印1-9
: : 使用者輸入2 印1-98 (11, 22, 33等重複的不印)
: : 使用者輸入3 印1-987 (121, 988, 667等有重複的不印)

Links booklink

Contact Us: admin [ a t ] ucptt.com