我需要一个程序从牌组中挑选四张牌并计算其总和 注意ace = 1,jack = 11,queen = 12,king = 13.计算它们的总和后,检查该总和是否等于24.如果是,记录下来。最后,程序应显示总和为24的组合数。
这就是我所拥有的:
def selfour():
total = 0
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for a in range(52):
for b in range(1, 52):
for c in range(2, 52):
for d in range(3, 52):
print(cards[a], cards[b], cards[c], cards[d])
if (cards[a] + cards[b] + cards[c] + cards[d]) == 24:
total += 1
return total
def main():
print(selfour())
main()
我不太确定这个程序是否会产生正确的答案,但效率很低。如果有人可以提供帮助以使这个代码更有效,那将是很好的。我相当肯定这不会得到正确的答案,所以对此的帮助也会很棒。
由于
答案 0 :(得分:8)
Itertools是你的朋友。你可以在一个班轮里做到这一点:
import itertools
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
def selfour():
return sum(sum(i) == 24 for i in itertools.combinations(cards, 4))
答案 1 :(得分:1)
你正在考虑这些牌彼此不相同,但是你并没有得到它。
for a in range(52):
for b in range(1, 52):
需要像:
for a in range(52):
for b in range(52):
if b == a:
continue
有一个名为itertools
的模块combinations
可以满足您的需求。有了它,你的嵌套for循环可以变成:
from itertools import combinations
for a in combinations(cards, 4):
if sum(a) == 24:
total += 1
答案 2 :(得分:0)
我不能100%确定这是否正确,但我能做到:
from itertools import combinations
def sel(it, cnt=4, val=24):
return sum(sum(_) == val for _ in combinations(it, cnt))
cards = # ...
print(sel(cards, 4, 24)) # => 12517
编辑:抱歉,我确定已发布新答案。我一出现就写这篇文章但在发布之前就分心了。
答案 3 :(得分:0)
这是我最终用于代码的内容:
import itertools
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
def selfour():
total = 0
for z in itertools.combinations(cards, 4):
if sum(z) == 24:
total += 1
return total
def main():
print(selfour())
main()
感谢用户的帮助,这段代码更加高效和干净。
此外,如果需要,其他初学者可以轻松地遵循这一点 -
-Thanks