[Tutor] Feed arguments to callback(?) function
trent shipley
trent.shipley at gmail.com
Tue Jun 6 00:58:56 EDT 2023
I want to take and arbitrary probability distribution function, send it
it's keyword arguments, and run it as the core of a generic dice rolling
program in Python (so it is accessible to the maximum number of
programmers),
# hackable_dice_roller
# from typing import Any, List, Tuple, Callable
from random import normalvariate, randrange, seed
# import operator
class DieRoll:
def __init__(self,
die, # a probability input function
transform=None, # a function to transform the result
returned by the PDF
**die_args): # Keyword:Value arguments to the PDF python
function (doesn't work)
self._die = die
self._transform = transform
self._die_args = die_args
def die_roll(self):
roll = self._die(self._die_args) # throws error
if self._transform is not None:
roll = self._transform(roll)
return roll
class IntegerDieRoll(DieRoll):
def __init__(self,
transform=None,
sides=6,
bottom=1):
super().__init__(die=randrange, # a random module pdf
transform=transform,
start=bottom, # say 1 on a 6 sided die
stop=bottom + sides, # 1 + 6 = 7, randrange
should return value 1 to 6 inclusive
step=1)
if sides <= 0:
raise ValueError("Parameter 'die' must be at least 1")
def die_roll(self):
return int(super().die_roll())
if __name__ == '__main__':
seed(0)
integer_die_roll = IntegerDieRoll()
print(integer_die_roll.die_roll())
----------
Traceback (most recent call last):
File "/usr/lib/python3.11/random.py", line 295, in randrange
istart = _index(start)
^^^^^^^^^^^^^
TypeError: 'dict_values' object cannot be interpreted as an integer
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File
"/home/trent/pythonworkspace/hackable_dice_roller/roll_instruction.py",
line 85, in <module>
print(integer_die_roll.die_roll())
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/home/trent/pythonworkspace/hackable_dice_roller/roll_instruction.py",
line 41, in die_roll
return int(super().die_roll())
^^^^^^^^^^^^^^^^^^
File
"/home/trent/pythonworkspace/hackable_dice_roller/roll_instruction.py",
line 21, in die_roll
roll = self._die(self._die_args.values())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/random.py", line 297, in randrange
istart = int(start)
^^^^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real
number, not 'dict_values'
Process finished with exit code 1
More information about the Tutor
mailing list