帮我完成这个 Python 3.x 自我挑战
这不是家庭作业。
我看到这篇文章赞扬了 Linq 库以及它的伟大组合学的东西,我心想: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)
谢谢!
This is not homework.
I saw this article praising Linq library and how great it is for doing combinatorics stuff, and I thought to myself: Python can do it in a more readable fashion.
After half hour of dabbing with Python I failed. Please finish where I left off. Also, do it in the most Pythonic and efficient way possible please.
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)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个简短的解决方案,使用 itertools.permutations:
我故意省略了检查 1 和 9 的整除性,因为它们总是令人满意的。
Here's a short solution, using itertools.permutations:
I've deliberately omitted the divisibility checks by 1 and by 9, since they'll always be satisfied.
这是我的解决方案。我喜欢自下而上的所有事情;-)。在我的机器上,它的运行速度比 Marks 快大约 580 倍(3.1 毫秒 vs. 1.8 秒):
编辑:另外,这有效,而且速度快两倍(1.6 毫秒):
Here's my solution. I like all things bottom-up ;-). On my machine it runs about 580 times faster (3.1 msecs vs. 1.8 secs) than Marks:
EDIT: Also, this works, and twice as fast (1.6 msecs):
这是我的解决方案(不像马克的那么优雅,但它仍然有效):
Here's my solution (not as elegant as Mark's, but it still works):
这是我的解决方案,它与 Marks 非常相似,但运行速度大约是 Marks 的两倍
this is my solution, it is very similar to Marks, but it runs about twice as fast