-5

我正在用python编写一个程序来将游戏从特征形式转换为正常形式。我已经阅读了一些类似问题的答案:大多数人说最好使用字典。但是我认为如果您想为键指定特定名称,问题仍然存在。

假设我想为三个玩家的游戏构建一个程序,这很容易:

v1 = int(raw_input("How much is worth the coalition v(1)?"))
v2 = int(raw_input("How much is worth the coalition v(2)?"))
v3 = int(raw_input("How much is worth the coalition v(3)?"))
v12 = int(raw_input("How much is worth the coalition v(1,2)?"))
v13 = int(raw_input("How much is worth the coalition v(1,3)?"))
v23 = int(raw_input("How much is worth the coalition v(2,3)?"))
v123 = int(raw_input("How much is worth the coalition v(1,2,3)?"))
# and then I continue with the program

但是,如果我想为 n 个玩家的游戏构建一个程序……当然,我可以构建一个字典,但我仍然不知道如何按照我想要的方式调用每个键(v1、v2、v3,. .. ...,v123..n)。有任何想法吗?

4

2 回答 2

0

最简单的方法是拥有一个容器类,创建一个空实例并根据需要为其添加属性:

class MyContainer(object):
    pass

my_container = MyContainer()
my_container.first_var = 1
my_container.next_var = "Hello"
...

但肯定有更好的方法,具体取决于您的应用程序。对于 Python3,您可以/应该省略对象基类。

如果您想动态创建变量名(无论这里为什么需要),您可以使用:

setattr(my_container, "a_string_with_the_name_of_the_attribute", "the value")
于 2015-04-23T20:25:25.027 回答
-1

我不是 Python 方面的专家,但我认为您还应该用其唯一的整数表示来表示每个联盟 $S$,即 $\sum_{i \in S}\, 2^{i-1}$。例如,联盟 $S={3,4}$ 表示为 $2^{3-1}+2^{4-1}=4+8=12$,而联盟 $S={2,3 ,4}$ 由 $2^{2-1}+2^{3-1}+2^{4-1}=2+4+8=14$ 给出。在 Matlab 中,四人 TU 游戏的所有联盟都可以通过

N=2^n-1;
S=1:N

而$n=4$,$N$是大联盟${1,2,3,4}$。这意味着您只需要通过像这样的数组来指定联合值

v = [0     0     5     0     0     0    40     0    10    40   100   100   160   190   250];

当然,联军顺序与你的做法不同。要看到这一点,请注意联盟 $S={1,2}$ 位于位置 $3$,值为 $5$ ($v({1,2})=5$),并且联盟 $S={ 3}$ 位于 $4$ 位置,值为 0 ($v({3})=0$)。我猜在 Python 下也存在一个命令,比如 Matlab 下的 bitget,可以在 $n=5$ 的情况下挑选出哪些位(玩家)属于数字(联盟)$27$。

为了演示,让我们计算上述游戏 $v$ 的 Shapley 值。我们只需要将联合值传递给函数 ShapleyValue() 即可获得

>> sh_v=ShapleyValue(v)

sh_v =

      29.5833   44.5833   73.7500  102.0833

我的 Matlab 博弈论工具箱提供了更多详细信息,可在此处找到:

http://www.mathworks.com/matlabcentral/fileexchange/35933-mattugames

于 2015-05-18T15:01:49.977 回答