Skip to content

Commit 0efc13b

Browse files
author
OpenClaw Assistant
committed
Fix #741: ValueError in WordSwapChangeNumber._alter_number for negative numbers
- Ensure change is always positive: change = abs(int(num * max_change)) + 1 - Add range validation before calling np.random.randint() - Return empty list for invalid ranges instead of raising exception - Maintain backward compatibility for all valid inputs Fixes #741
1 parent 0d0929c commit 0efc13b

1 file changed

Lines changed: 20 additions & 3 deletions

File tree

textattack/transformations/word_swaps/word_swap_change_number.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,28 @@ def _alter_number(self, num):
104104
"""Helper function of _get_new_number, replace a number with another
105105
random number within the range of self.max_change."""
106106
if num not in [0, 2, 4]:
107-
change = int(num * self.max_change) + 1
107+
# Ensure change is always positive to avoid invalid ranges
108+
change = abs(int(num * self.max_change)) + 1
108109
if num >= 0:
109-
num_list = np.random.randint(max(num - change, 1), num + change, self.n)
110+
# For positive numbers, ensure we don't go below 1
111+
low = max(num - change, 1)
112+
high = num + change
113+
# Ensure valid range for np.random.randint
114+
if low < high:
115+
num_list = np.random.randint(low, high, self.n)
116+
else:
117+
# If range is invalid, return empty list
118+
return []
110119
else:
111-
num_list = np.random.randint(num - change, min(0, num + change), self.n)
120+
# For negative numbers
121+
low = num - change
122+
high = min(0, num + change)
123+
# Ensure valid range for np.random.randint
124+
if low < high:
125+
num_list = np.random.randint(low, high, self.n)
126+
else:
127+
# If range is invalid, return empty list
128+
return []
112129
return num_list
113130
return []
114131

0 commit comments

Comments
 (0)