Skip to content

Commit c6fb0df

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 c6fb0df

1 file changed

Lines changed: 21 additions & 3 deletions

File tree

textattack/transformations/word_swaps/word_swap_change_number.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,29 @@ 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
109+
108110
if num >= 0:
109-
num_list = np.random.randint(max(num - change, 1), num + change, self.n)
111+
# For positive numbers, ensure we don't go below 1
112+
low = max(num - change, 1)
113+
high = num + change
114+
# Ensure valid range for np.random.randint
115+
if low < high:
116+
num_list = np.random.randint(low, high, self.n)
117+
else:
118+
# If range is invalid, return empty list
119+
return []
110120
else:
111-
num_list = np.random.randint(num - change, min(0, num + change), self.n)
121+
# For negative numbers
122+
low = num - change
123+
high = min(0, num + change)
124+
# Ensure valid range for np.random.randint
125+
if low < high:
126+
num_list = np.random.randint(low, high, self.n)
127+
else:
128+
# If range is invalid, return empty list
129+
return []
112130
return num_list
113131
return []
114132

0 commit comments

Comments
 (0)