Ham*_*jan 8 python puzzle combinatorics python-3.x
这不是功课.
我看到这篇文章赞扬了Linq库以及组合工具的优点,我想我自己:Python可以用更易读的方式来做.
用Python轻拍半小时后,我失败了.请在我离开的地方完成.另外,请以最恐怖和最有效的方式来做.
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)
谢谢!
Mar*_*son 23
这是一个简短的解决方案,使用itertools.permutations:
from itertools import permutations
def is_solution(seq):
    return all(int(seq[:i]) % i == 0 for i in range(2, 9))
for p in permutations('123456789'):
    seq = ''.join(p)
    if is_solution(seq):
        print(seq)
我故意省略了1和9的可分性检查,因为它们总会得到满足.
| 归档时间: | 
 | 
| 查看次数: | 434 次 | 
| 最近记录: |