Skip to content

Commit

Permalink
修复背包算法可能产生的死循环
Browse files Browse the repository at this point in the history
  • Loading branch information
AlongWY committed Sep 17, 2024
1 parent 1067708 commit c7a8590
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/llamafactory/data/processors/processor_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ def greedy_knapsack(numbers: List[int], capacity: int) -> List[List[int]]:
r"""
An efficient greedy algorithm with binary search for the knapsack problem.
"""
# filter out numbers that are larger than the capacity
numbers = [number for number in numbers if number <= capacity]
numbers.sort() # sort numbers in ascending order for binary search
knapsacks = []

Expand All @@ -43,6 +45,10 @@ def greedy_knapsack(numbers: List[int], capacity: int) -> List[List[int]]:
remaining_capacity -= numbers[index] # update the remaining capacity
current_knapsack.append(numbers.pop(index)) # add the number to knapsack

# avoid endless loop
if remaining_capacity == capacity:
break

knapsacks.append(current_knapsack)

return knapsacks
Expand Down

0 comments on commit c7a8590

Please sign in to comment.