Skip to content

Commit fdd8ffb

Browse files
committed
Changing the input be any iterable for transformer.
- Removing a redundant import? - Adding nicer docstring.
1 parent e0c0ea6 commit fdd8ffb

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

axelrod/strategy_transformers.py

+14-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import inspect
1010
import random
11-
from types import FunctionType
11+
import collections
1212
from numpy.random import choice
1313

1414
from .actions import Actions, flip_action
@@ -246,6 +246,16 @@ def mixed_wrapper(player, opponent, action, probability, m_player):
246246
of players or a single player.
247247
248248
In essence creating a mixed strategy.
249+
250+
Parameters
251+
----------
252+
253+
probability: a float (or integer: 0 or 1) OR an iterable representing a
254+
an incomplete probability distribution (entries to do not have to sum to
255+
1). Eg: 0, 1, [.5,.5], (.5,.3)
256+
m_players: a single player class or iterable representing set of player
257+
classes to mix from.
258+
Eg: axelrod.TitForTat, [axelod.Cooperator, axelrod.Defector]
249259
"""
250260

251261
# If a single probability, player is passed
@@ -254,14 +264,15 @@ def mixed_wrapper(player, opponent, action, probability, m_player):
254264
probability = [probability]
255265

256266
# If a probability distribution, players is passed
257-
if isinstance(probability, list) and isinstance(m_player, list):
267+
if isinstance(probability, collections.Iterable) and \
268+
isinstance(m_player, collections.Iterable):
258269
mutate_prob = sum(probability) # Prob of mutation
259270
if mutate_prob > 0:
260271
# Distribution of choice of mutation:
261272
normalised_prob = [prob / float(mutate_prob)
262273
for prob in probability]
263274
if random.random() < mutate_prob:
264-
p = choice(m_player, p=normalised_prob)()
275+
p = choice(list(m_player), p=normalised_prob)()
265276
p.history = player.history
266277
return p.strategy(opponent)
267278

axelrod/tests/unit/test_strategy_transformers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ def test_apology(self):
212212
p1.play(p2)
213213
self.assertEqual(p1.history, [D, D, C, D, D, C])
214214

215-
def test_mutate(self):
215+
def test_mixed(self):
216216
"""Tests the MixedTransformer."""
217217
probability = 1
218218
MD = MixedTransformer(probability, axelrod.Cooperator)(axelrod.Defector)
@@ -248,7 +248,7 @@ def test_mutate(self):
248248
self.assertEqual(p1.history, [C, C, C, C, C])
249249

250250
# Decorate a cooperator putting all weight on Defector
251-
probability = [0, 0, 1]
251+
probability = (0, 0, 1) # Note can also pass tuple
252252
strategies = [axelrod.TitForTat, axelrod.Grudger, axelrod.Defector]
253253
MD = MixedTransformer(probability, strategies)(axelrod.Cooperator)
254254

0 commit comments

Comments
 (0)