我需要一个程序来从一副牌中挑选四张牌并计算它们的总和。
请注意,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()
我不太确定这个程序是否会产生正确的答案,但它效率很低。如果有人可以提供帮助以提高此代码的效率,那就太好了。我相当确定这不会产生正确的答案,所以帮助也很好。
谢谢
Itertools 是您的 friend 。您可以在一行中执行此操作:
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))
我是一名优秀的程序员,十分优秀!