Skip to content

pydsa.search

PAIRS module-attribute

PAIRS = (('left', 'right'), ('low', 'high'), ('lo', 'hi'))

TRUE_MARK module-attribute

TRUE_MARK = '[bold green]✓[/bold green]'

FALSE_MARK module-attribute

FALSE_MARK = '[bold red]✗[/bold red]'

MID_MARK module-attribute

MID_MARK = '[bold yellow]▼[/bold yellow]'

IN_RANGE module-attribute

IN_RANGE = '[cyan]█[/cyan]'

DROPPED module-attribute

DROPPED = '[dim]·[/dim]'
viz_binary_search(
    func: Optional[Callable] = None,
    width: Optional[int] = None,
)

Trace a binary search: one bar per step, mid marked ✓/✗ by ok(mid).

Source code in pydsa/search.mu
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def viz_binary_search(func: Callable?=none, width: int?=none)
  """Trace a binary search: one bar per step, mid marked ✓/✗ by ok(mid)."""
  width = width or min(100, shutil.get_terminal_size().columns) if none
  def decorator(f: Callable) -> Callable
    def wrapper(*args, **kwargs)
      viz = _Viz(f, width)
      bound = inspect.signature(f).bind(*args, **kwargs)
      for name, v in bound.arguments.items()
        if callable(v)
          bound.arguments[name] = _record(viz.calls, v, name)
      args, kwargs = bound.args, bound.kwargs
      old = sys.gettrace()
      sys.settrace(viz.trace)
      try
        result = f(*args, **kwargs)
      finally
        sys.settrace(old)
      viz.finish(result)
      result
    wrapper
  callable(func) ? decorator(func) : decorator
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def viz_binary_search(func: Optional[Callable] = None, width: Optional[int] = None):
    """Trace a binary search: one bar per step, mid marked ✓/✗ by ok(mid)."""
    width = (min(100, shutil.get_terminal_size().columns) if width == None else width)
    def decorator(f: Callable) -> Callable:
        def wrapper(*args, **kwargs):
            viz = _Viz(f, width)
            bound = inspect.signature(f).bind(*args, **kwargs)
            for name, v in bound.arguments.items():
                if callable(v):
                    bound.arguments[name] = _record(viz.calls, v, name)
            args, kwargs = bound.args, bound.kwargs
            old = sys.gettrace()
            sys.settrace(viz.trace)
            try:
                result = f(*args, **kwargs)
            finally:
                sys.settrace(old)
            viz.finish(result)
            return result
        return wrapper
    return decorator(func) if callable(func) else decorator

first_true

first_true(
    lo: int, hi: int, ok: Callable[[int], bool]
) -> int

Smallest x in [lo, hi] with ok(x) True; ok is False then True.

Returns hi + 1 when ok is False on the whole range.

Source code in pydsa/search.mu
148
149
150
151
152
def first_true(lo: int, hi: int, ok: int -> bool) -> int
  """Smallest x in [lo, hi] with ok(x) True; ok is False then True.

  Returns hi + 1 when ok is False on the whole range."""
  lo + bisect_left(range(lo, hi + 1), true, key=ok)
163
164
165
166
167
def first_true(lo: int, hi: int, ok: Callable[[int], bool]) -> int:
    """Smallest x in [lo, hi] with ok(x) True; ok is False then True.

    Returns hi + 1 when ok is False on the whole range."""
    return lo + bisect_left(range(lo, hi + 1), True, key=ok)

last_true

last_true(
    lo: int, hi: int, ok: Callable[[int], bool]
) -> int

Largest x in [lo, hi] with ok(x) True; ok is True then False.

Returns lo - 1 when ok is False on the whole range.

Source code in pydsa/search.mu
154
155
156
157
158
def last_true(lo: int, hi: int, ok: int -> bool) -> int
  """Largest x in [lo, hi] with ok(x) True; ok is True then False.

  Returns lo - 1 when ok is False on the whole range."""
  first_false(lo, hi, ok) - 1
170
171
172
173
174
def last_true(lo: int, hi: int, ok: Callable[[int], bool]) -> int:
    """Largest x in [lo, hi] with ok(x) True; ok is True then False.

    Returns lo - 1 when ok is False on the whole range."""
    return first_false(lo, hi, ok) - 1

first_false

first_false(
    lo: int, hi: int, ok: Callable[[int], bool]
) -> int

Smallest x in [lo, hi] with ok(x) False; ok is True then False.

Returns hi + 1 when ok is True on the whole range.

Source code in pydsa/search.mu
160
161
162
163
164
def first_false(lo: int, hi: int, ok: int -> bool) -> int
  """Smallest x in [lo, hi] with ok(x) False; ok is True then False.

  Returns hi + 1 when ok is True on the whole range."""
  first x in lo..hi if not ok(x)
177
178
179
180
181
def first_false(lo: int, hi: int, ok: Callable[[int], bool]) -> int:
    """Smallest x in [lo, hi] with ok(x) False; ok is True then False.

    Returns hi + 1 when ok is True on the whole range."""
    return lo + bisect_left(range(lo, hi + 1), True, key=lambda x: not ok(x))

last_false

last_false(
    lo: int, hi: int, ok: Callable[[int], bool]
) -> int

Largest x in [lo, hi] with ok(x) False; ok is False then True.

Returns lo - 1 when ok is True on the whole range.

Source code in pydsa/search.mu
166
167
168
169
170
def last_false(lo: int, hi: int, ok: int -> bool) -> int
  """Largest x in [lo, hi] with ok(x) False; ok is False then True.

  Returns lo - 1 when ok is True on the whole range."""
  first_true(lo, hi, ok) - 1
184
185
186
187
188
def last_false(lo: int, hi: int, ok: Callable[[int], bool]) -> int:
    """Largest x in [lo, hi] with ok(x) False; ok is False then True.

    Returns lo - 1 when ok is True on the whole range."""
    return first_true(lo, hi, ok) - 1

min_chunks

min_chunks(nums: list[int], cap: int) -> float

Fewest contiguous chunks of nums with every chunk summing to at most cap.

Greedy: extend the current chunk while it fits, cut when the next number would push it past cap. Returns inf when a single number exceeds cap.

Source code in pydsa/search.mu
172
173
174
175
176
177
178
179
180
181
182
183
184
def min_chunks(nums: [int], cap: int) -> float
  """Fewest contiguous chunks of nums with every chunk summing to at most cap.

  Greedy: extend the current chunk while it fits, cut when the next number
  would push it past cap. Returns inf when a single number exceeds cap."""
  ret chunks, total = 1, 0
  for n in nums
    if n > cap
      return inf
    if total + n > cap
      chunks, total = chunks + 1, n
    else
      total += n
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def min_chunks(nums: list[int], cap: int) -> float:
    """Fewest contiguous chunks of nums with every chunk summing to at most cap.

    Greedy: extend the current chunk while it fits, cut when the next number
    would push it past cap. Returns inf when a single number exceeds cap."""
    chunks, total = 1, 0
    for n in nums:
        if n > cap:
            return inf
        if total + n > cap:
            chunks, total = chunks + 1, n
        else:
            total += n
    return chunks