fix behaviour of random values on empty data sets, add tests
This commit is contained in:
@@ -122,9 +122,9 @@ class DataSource:
|
||||
"""
|
||||
|
||||
# If there is no data for the specified option, stop now.
|
||||
flattened = [option]
|
||||
flattened = []
|
||||
if not self.data[option]:
|
||||
return random.choice(flattened) if rand else flattened
|
||||
raise ValueError(f"There is no data for '{option}' in your data source.")
|
||||
|
||||
if hasattr(self.data[option], 'keys'):
|
||||
# if the option is a dict, we assume the values are lists; we select a random item
|
||||
|
||||
+8
-1
@@ -22,7 +22,14 @@ class WeightedSet:
|
||||
self.members, self.weights = list(zip(*weighted_members))
|
||||
|
||||
def random(self) -> str:
|
||||
return random.choices(self.members, self.weights)[0]
|
||||
nonzero_members = []
|
||||
nonzero_weights = []
|
||||
for i in range(self.weights):
|
||||
if float(self.weights[i]) == 0.0:
|
||||
continue
|
||||
nozero_members.append(self.members[i])
|
||||
nozero_weights.append(self.weights[i])
|
||||
return random.choices(nonzero_members, nonzero_weights)[0]
|
||||
|
||||
def __add__(self, obj):
|
||||
ws = WeightedSet()
|
||||
|
||||
Reference in New Issue
Block a user