首页 > 解决方案 > Is it possible to rewrite the outcome of 2*func(x) to be func(x) + func(x) in Python?

问题描述

This problem has been intriguing, even though it's not necessarily neat. I have the following code:

import random

def d(m):
    return random.randint(1, m)

print(3*d(6))

This will print the returned value of d(6) and multiply that by 3. What I would like to have is to define a set of symbols so I can set that 3*d(6) will instead return: d(6) + d(6) + d(6). Alternatively is it possible to set the expression '3d6' to return what I want in a general case for XdY?

Is this solvable with wrappers / addition of symbols or do I have to go deeper and change stuff in the interpreter?

I'm trying to make the program read more naturally for the gaming genre. In tabletop gaming, people say "2d6", which means 'throw two 6-sided dice'. This has a different probability density function compared to 2*d(6).

标签: python

解决方案


您不能产生int3*d(6)的效果d(6)+d(6)+d(6) d(6)返回 int。如果您正在创建表示概率分布或类似内容的对象,您可以__rmul__按照您想要的方式重载,但不能使用整数。

你也不能3d6评估你想要的。3d6不是有效的 Python 令牌。您将不得不更改并重新编译 Python 源代码以生成您自己的具有更改语法的 Python 变体,这将是很多工作而没有什么好处。


推荐阅读