這不是家庭作業。幫我完成這個Python 3.x自我挑戰
我看到this article praising Linq library and how great it is做combinatorics的東西,我心想:Python可以以更具可讀性的方式做到這一點。
用Python打了半個小時後我失敗了。請結束我離開的地方。另外,請儘可能採用最爲Pythonic和高效的方式。
from itertools import permutations
from operator import mul
from functools import reduce
glob_lst = []
def divisible(n): return (sum(j*10^i for i,j in enumerate(reversed(glob_lst))) % n == 0)
oneToNine = list(range(1, 10))
twoToNine = oneToNine[1:]
for perm in permutations(oneToNine, 9):
for n in twoToNine:
glob_lst = perm[1:n]
#print(glob_lst)
if not divisible(n):
continue
else:
# Is invoked if the loop succeeds
# So, we found the number
print(perm)
謝謝!
待辦事項你想要Pythonic還是最有效的?他們可能是非常不同的東西。 :) – 2010-04-15 23:07:21
我想這一切,我想現在;)嗯...每一個以及兩者之一。沒有最好的答案,但我不得不選擇一個。如果您願意的話,請包括timeit one-liner進行性能測試。 – 2010-04-15 23:13:28
爲什麼你在可分的函數中使用按位異或?你的意思是**而不是^? – dan04 2010-04-16 01:57:17