这是一个允许您选择两个玩家的策略的解决方案。您可以使用它来解决给定的问题,但您也可以将两个玩家的策略设置为“optimal_strategy”以找到极小极大解决方案。
import random
def greedy_strategy(s0, s1, cards, i, j, cache):
if i == j: return 0
if cards[i] >= cards[j - 1]:
return cards[i] - s1(s1, s0, cards, i + 1, j, cache)
else:
return cards[j - 1] - s1(s1, s0, cards, i, j - 1, cache)
def optimal_strategy(s0, s1, cards, i, j, cache):
if i == j: return 0
key = (i, j)
if key not in cache:
left = cards[i] - s1(s1, s0, cards, i + 1, j, cache)
right = cards[j - 1] - s1(s1, s0, cards, i, j - 1, cache)
cache[key] = max(left, right)
return cache[key]
def score_play(cards, s0, s1):
# How many points you'll win by
adv = s0(s0, s1, cards, 0, len(cards), {})
# my_score + opp_score = sum(cards)
# my_score - opp_score = adv
# adding: 2 * my_score = sum(cards) + adv
# Therefore my_score is this...
return (sum(cards) + adv) // 2
for _ in xrange(10):
cards = range(20)
random.shuffle(cards)
print cards, score_play(cards, optimal_strategy, greedy_strategy)