Dataset / curation /v3 /scripts /author_pilot.py
dsfasdfaserwer's picture
Add verified Python TACO v3 pilot part 1/5 (2 rows)
22c9027 verified
Raw History Blame Contribute Delete
23.9 kB
"""Pilot annotations individually authored and reviewed by the Qwen assistant.
These are synthetic, code-aligned solution summaries, NOT human annotations or
reconstructions of a model's private reasoning. Running this file reproduces the
reviewed pilot; it does not claim to generate arbitrary future annotations.
"""
from pathlib import Path
import json
import textwrap
ROOT = Path(__file__).resolve().parents[1]
ITEMS = [
{
'index': 5,
'title': 'Count 2/3/5-smooth numbers in inclusive ranges',
'instruction': "Can you write a Python program that counts the integers in a range whose only prime factors are 2, 3, or 5? Count 1 as valid too. I need to process up to 20 ranges: each input line contains m and n, with 1 <= m <= n <= 1,000,000, and a line containing just 0 ends the input. Print one count per range, including both endpoints. For example, the range 3 to 8 should give 5.",
'chain_of_thought': "Every valid number has the form 2^a * 3^b * 5^c for nonnegative exponents. Generate these products with integer multiplication, stopping each loop at the maximum input value; unique prime factorization prevents duplicates and includes 1. After sorting the valid values, the count in [m, n] is the position after n minus the position before m. This handles singleton ranges and avoids scanning up to a million integers for every query. With H valid values and Q queries, the implementation takes O(H log H + Q log H) time and O(H) auxiliary space.",
'doc': "Reads inclusive range queries from standard input and prints one answer per line. A line containing 0 is a terminator, not a query; integer arithmetic avoids floating-point boundary errors.",
'changes': ['Replaced floating-point exponent limits with bounded integer multiplication.', 'Removed unnecessary products above the supported limit and unused imports.', 'Made the zero sentinel explicit and separated generation from input handling.'],
'contract_note': 'Same mathematical task and stdin contract; irrelevant historical background omitted.',
'topics': ['number theory', 'range counting'],
'code': '''
from bisect import bisect_left, bisect_right
import sys
def smooth_numbers(limit: int) -> list[int]:
values = []
power_of_two = 1
while power_of_two <= limit:
product_23 = power_of_two
while product_23 <= limit:
product_235 = product_23
while product_235 <= limit:
values.append(product_235)
product_235 *= 5
product_23 *= 3
power_of_two *= 2
return sorted(values)
def main() -> None:
values = smooth_numbers(1_000_000)
for line in sys.stdin:
fields = line.split()
if not fields:
continue
if fields == ["0"]:
break
lower, upper = map(int, fields)
print(bisect_right(values, upper) - bisect_left(values, lower))
if __name__ == "__main__":
main()
'''
},
{
'index': 6,
'title': 'Smallest digit rearrangement without a leading zero',
'instruction': "I need a Python function smallest_rearrangement(s) that rearranges the digits of a decimal string into the smallest possible number without a leading zero. Keep every digit, including repeats, and return a string rather than an integer; the input can have up to 100,000 digits. If the string consists entirely of zeros, leave it unchanged. For example, '846903' should become '304689', and '55010' should become '10055'. You can assume s is a nonempty string of ASCII digits.",
'chain_of_thought': "The first digit must be the smallest available nonzero digit; choosing a larger one would make the result larger regardless of the suffix. Once that digit is fixed, arranging all remaining digits in ascending order gives the smallest suffix, with zeros now allowed. A table of ten digit frequencies preserves multiplicities and avoids sorting a very long input. An all-zero string is returned unchanged as specified. Time is O(N), with O(1) counting state and O(N) space for the returned string.",
'doc': "Returns the rearranged digits without converting a potentially huge value to an integer. The input string is not modified, and the all-zero case preserves its original length.",
'changes': ['Replaced comparison sorting and repeated string concatenation with ten digit counts.', 'Exposed a standalone, descriptively named function instead of the judge class.', 'Made the previously unspecified all-zero behavior explicit, matching the selected source implementation.'],
'contract_note': 'Original examples preserved; all-zero behavior clarified; class wrapper removed through an explicit test adapter.',
'topics': ['digit manipulation', 'counting'],
'code': '''
def smallest_rearrangement(s: str) -> str:
counts = [0] * 10
for digit in s:
counts[ord(digit) - ord("0")] += 1
for first in range(1, 10):
if counts[first]:
counts[first] -= 1
suffix = "".join(str(digit) * counts[digit] for digit in range(10))
return str(first) + suffix
return s
'''
},
{
'index': 7,
'title': 'Minimum finishing time for contiguous painting assignments',
'instruction': "Please write a Python function minimum_paint_time(boards, painters). The boards are in a fixed order and take one unit of time per unit of length to paint. All painters start together. Each painter may take one contiguous group of whole boards, or do nothing; boards cannot be split or reordered. Return the least possible finishing time. There can be up to 100,000 positive board lengths, each at most 100,000, and between 1 and 100,000 painters. For boards [5, 10, 30, 20, 15] and 3 painters, the answer should be 35. Please leave the input list unchanged.",
'chain_of_thought': "A candidate finishing time is feasible if the boards can be covered by at most the available number of contiguous groups whose sums do not exceed it. Filling each group as far as possible uses the fewest groups for that limit because all lengths are positive. Feasibility is monotone: increasing the limit cannot require more painters. Search between the longest board and the total length, keeping the smallest feasible limit. This takes O(N log(sum(boards))) time and O(1) auxiliary space; unused painters are allowed.",
'doc': "Returns an integer time and does not change boards. The result is the total length for one painter and the longest board when there are enough painters for every board.",
'changes': ['Preserved the feasibility-search algorithm with clearer names and type hints.', 'Removed redundant n parameter and judge-class wrapper.', 'Documented positive lengths, whole-board assignments and permitted idle painters.'],
'contract_note': 'Same optimization problem; n is inferred from boards in the public function.',
'topics': ['partitioning', 'monotone feasibility'],
'code': '''
def minimum_paint_time(boards: list[int], painters: int) -> int:
lower, upper = max(boards), sum(boards)
while lower < upper:
limit = (lower + upper) // 2
used = 1
current = 0
for length in boards:
if current + length > limit:
used += 1
current = length
else:
current += length
if used <= painters:
upper = limit
else:
lower = limit + 1
return lower
'''
},
{
'index': 14,
'title': 'Shortest substring covering every distinct input character',
'instruction': "Can you make a Python function smallest_covering_window(text) that returns the length of the shortest contiguous substring containing every distinct character that appears anywhere in text? It needs to be case-sensitive, and repeated occurrences of a character do not create extra requirements. The input is a nonempty string of English letters, up to 100,000 characters. For 'AABBBCBBAC' the answer is 3, and for 'aaab' it is 2. I only need the length, not the substring.",
'chain_of_thought': "The requirement is one occurrence of each distinct character, so track the frequencies in a moving window. Extend its right edge until it covers the full character set, then repeatedly advance the left edge while coverage remains complete, recording the shortest valid length. Removing a character's final occurrence makes the window incomplete and stops shrinking. Both boundaries move only forward, giving expected O(N) time with a dictionary and O(U) auxiliary space for U distinct characters. Uppercase and lowercase letters remain separate keys.",
'doc': "Returns a length, not the matching text. Character counts retain coverage when an extra copy leaves the window; a string containing just one distinct character therefore returns 1.",
'changes': ['Replaced variables shadowing str and dict with descriptive names.', 'Used an explicit frequency dictionary and removed zero-count entries.', 'Removed judge-class wrapper without changing case-sensitive substring semantics.'],
'contract_note': 'Same source function semantics; standalone public name and nonempty-input contract.',
'topics': ['strings', 'sliding windows'],
'code': '''
def smallest_covering_window(text: str) -> int:
required = len(set(text))
counts = {}
left = 0
best = len(text)
for right, character in enumerate(text):
counts[character] = counts.get(character, 0) + 1
while len(counts) == required:
best = min(best, right - left + 1)
outgoing = text[left]
counts[outgoing] -= 1
if counts[outgoing] == 0:
del counts[outgoing]
left += 1
return best
'''
},
{
'index': 25,
'title': 'Maximum hindsight profit with unlimited single-share trades',
'instruction': "Write a Python function maximum_profit(prices) for a historical list of daily stock prices. I want the best profit that could have been achieved in hindsight with any number of buys and sells, while holding at most one share at a time. Assume no fees, cooldown or short selling; doing no trades is allowed. Return only the profit and leave the list unchanged. There are 1 to 100,000 days with positive integer prices up to 100,000. For [7, 1, 5, 3, 6, 4], the result should be 7.",
'chain_of_thought': "On any rising stretch, buying at its start and selling at its end earns the sum of its positive adjacent increases. Falling steps should be excluded because selling before the drop and buying afterward cannot reduce profit when fees and cooldowns are absent. Adding every positive day-to-day increase therefore captures all profitable stretches without overlapping holdings. Flat or decreasing lists produce zero profit. The scan takes O(N) time and O(1) auxiliary space.",
'doc': "Computes a hindsight optimum for the stated simplified trading rules, not a forecast. Its result would not generally apply unchanged if fees, limited trades or cooldowns were added.",
'changes': ['Simplified the selected positive-difference implementation.', 'Removed redundant n parameter, index bookkeeping and judge wrapper.', 'Clarified the trading assumptions under which the formula is valid.'],
'contract_note': 'Same unlimited-transactions optimization; explicit hindsight interpretation and unchanged input.',
'topics': ['sequence optimization', 'greedy accounting'],
'code': '''
def maximum_profit(prices: list[int]) -> int:
return sum(
max(0, prices[day] - prices[day - 1])
for day in range(1, len(prices))
)
'''
},
{
'index': 26,
'title': 'Longest strictly nestable chain from two doll collections',
'instruction': "I have two collections of nesting dolls and want to find the longest single chain I can make using dolls from either collection. A doll fits inside another only when both its height and radius are strictly smaller; equal heights or equal radii do not fit. Please write a Python stdin program. Each dataset gives n, then n lines of height and radius, then m and another m such lines. A line containing 0 in place of n ends the input. Each collection has 1 to 100 dolls, dimensions are positive integers below 1,000, and no two dolls have identical dimensions. Print the largest possible number of dolls in one chain for each dataset.",
'chain_of_thought': "Combine the two collections and order dolls by increasing height. For equal heights, put larger radii first so that a strictly increasing sequence of radii cannot mistakenly use two dolls of the same height. Maintain the smallest possible ending radius for each achievable chain length; replacing the first ending radius that is at least the current radius keeps future extensions possible without allowing equal radii to extend a chain. The number of maintained endings is the maximum chain length. For M dolls, sorting and updates take O(M log M) time and O(M) auxiliary space.",
'doc': "Uses both collections together and reports a chain length per input dataset. The strict comparisons in both dimensions are essential; merely sorting height and radius in the same ascending order would mishandle equal heights.",
'changes': ['Replaced quadratic subsequence scanning with logarithmic ending-radius updates.', 'Preserved descending-radius ordering for equal heights.', 'Separated chain calculation from the original two-collection input protocol.'],
'contract_note': 'Same explicit dimensional constraints and stdin protocol; decorative source illustration is not required.',
'topics': ['two-dimensional ordering', 'subsequences'],
'code': '''
from bisect import bisect_left
import sys
def longest_chain(dolls: list[tuple[int, int]]) -> int:
endings = []
for height, radius in sorted(dolls, key=lambda doll: (doll[0], -doll[1])):
position = bisect_left(endings, radius)
if position == len(endings):
endings.append(radius)
else:
endings[position] = radius
return len(endings)
def main() -> None:
values = iter(map(int, sys.stdin.buffer.read().split()))
for first_count in values:
if first_count == 0:
break
dolls = [(next(values), next(values)) for _ in range(first_count)]
second_count = next(values)
dolls.extend((next(values), next(values)) for _ in range(second_count))
print(longest_chain(dolls))
if __name__ == "__main__":
main()
'''
},
{
'index': 30,
'title': 'Total active time of overlapping equal-duration events',
'instruction': "I need a Python helper total_active_time(times, duration). Each timestamp starts an effect lasting duration time units, but overlapping effects do not add extra active time. Return the total time covered by at least one effect. The timestamps are sorted in nondecreasing order, duplicates are possible, and an empty list or zero duration should return 0. Values are nonnegative integers no larger than 10,000,000 and there can be up to 10,000 timestamps. For [1, 4] with duration 2 return 4; for [1, 2] with duration 2 return 3. Please don't modify the list.",
'chain_of_thought': "Treat an event at t as the half-open interval [t, t + duration). The first event contributes its full duration. Since timestamps are sorted and all durations are equal, each later event adds the smaller of duration and the gap from the previous timestamp: a smaller gap overlaps, while a larger gap leaves the new interval separate. Duplicate timestamps add nothing, and empty input or zero duration covers no time. The implementation uses O(N) time and O(1) auxiliary space.",
'doc': "Computes the length of the union, so touching intervals and overlapping intervals are both handled without double-counting. It assumes sorted timestamps; it does not silently sort or alter the input.",
'changes': ['Reframed the game-specific source problem as equal-duration event coverage.', 'Simplified the overlap accounting to one adjacent-gap scan without slicing.', 'Removed the judge-class wrapper and made empty/zero-duration behavior explicit.'],
'contract_note': 'Same interval-union semantics and allowed nonnegative values; renamed standalone function.',
'topics': ['interval coverage', 'sequence processing'],
'code': '''
def total_active_time(times: list[int], duration: int) -> int:
if not times or duration == 0:
return 0
total = duration
for index in range(1, len(times)):
total += min(duration, times[index] - times[index - 1])
return total
'''
},
{
'index': 50,
'title': 'Sum of greatest common divisors over bounded sequences',
'instruction': "Please write a Python program for this counting problem: consider all sequences of length N whose entries are integers from 1 through K. Add up the greatest common divisor of each sequence and print the sum modulo 1,000,000,007. Input is one line containing N and K, both at most 100,000, with N at least 2 and K at least 1. For input '3 2', the output is 9. I need it to work at those limits rather than explicitly list the sequences.",
'chain_of_thought': "For a positive integer d, there are floor(K/d)^N sequences whose entries are all divisible by d. That includes sequences with gcd equal to any larger multiple of d. Process d in descending order and subtract the already-counted sequences for those larger multiples to obtain the count with gcd exactly d. Weight that count by d and sum modulo the requested modulus. Modular exponentiation avoids constructing huge powers. Time is O(K log K + K log N) and auxiliary space is O(K).",
'doc': "Computes exact gcd counts modulo 1,000,000,007 rather than enumerating K^N sequences. Python's three-argument pow performs modular exponentiation directly.",
'changes': ['Named the modulus and exact-gcd count array explicitly.', 'Reduced inside-loop modulo operations while preserving modular arithmetic.', 'Separated the calculation into a reusable function and a stdin entry point.'],
'contract_note': 'Original counting task, bounds, sample and stdin interface retained.',
'topics': ['number theory', 'divisor counting', 'modular arithmetic'],
'code': '''
MODULUS = 1_000_000_007
def gcd_sequence_sum(length: int, upper_bound: int) -> int:
exact = [0] * (upper_bound + 1)
for divisor in range(upper_bound, 0, -1):
count = pow(upper_bound // divisor, length, MODULUS)
for multiple in range(2 * divisor, upper_bound + 1, divisor):
count -= exact[multiple]
exact[divisor] = count % MODULUS
return sum(divisor * exact[divisor] for divisor in range(1, upper_bound + 1)) % MODULUS
if __name__ == "__main__":
n, k = map(int, input().split())
print(gcd_sequence_sum(n, k))
'''
},
{
'index': 51,
'title': 'Can two arrays be paired to meet a minimum sum?',
'instruction': "Can you write a Python program that checks whether two equal-length arrays can be rearranged so every paired sum is at least a given threshold? The first input line is the number of queries q. Each query has a line n k, then n integers for A and n for B. Print YES if a suitable pairing exists, otherwise NO. There are at most 10 queries, n is between 1 and 1,000, k is between 1 and 1,000,000,000, and array values are between 0 and 1,000,000,000. For A = [2, 1, 3], B = [7, 8, 9] and k = 10, the answer is YES. The original array order does not have to be preserved in the pairing.",
'chain_of_thought': "Pair the smallest element of A with the largest element of B, then continue in opposite sorted orders. If the smallest remaining A cannot meet the threshold with the largest remaining B, no pairing can work. Otherwise this pair is safe: in any valid arrangement, exchanging partners to make it leaves the other A, which is at least as large, with a still-sufficient partner. Repeating that exchange argument justifies checking all opposite-order pairs. Sorting takes O(N log N) time and the sorted copies take O(N) auxiliary space.",
'doc': "The program prints one YES/NO answer per query and does not enumerate permutations. The pairing check uses sorted copies, so its helper does not mutate either input array.",
'changes': ['Preserved the opposite-order pairing algorithm with a non-mutating helper.', 'Removed manual loop flags and unnecessary mutable list sorting.', 'Kept the exact query format and YES/NO output contract.'],
'contract_note': 'Same source decision problem and stdin protocol; misleading source explanation typo omitted.',
'topics': ['matching feasibility', 'sorting', 'exchange arguments'],
'code': '''
import sys
def can_pair(threshold: int, first: list[int], second: list[int]) -> bool:
return all(
left + right >= threshold
for left, right in zip(sorted(first), sorted(second, reverse=True))
)
def main() -> None:
values = iter(map(int, sys.stdin.buffer.read().split()))
queries = next(values)
for _ in range(queries):
size, threshold = next(values), next(values)
first = [next(values) for _ in range(size)]
second = [next(values) for _ in range(size)]
print("YES" if can_pair(threshold, first, second) else "NO")
if __name__ == "__main__":
main()
'''
},
{
'index': 59,
'title': 'Fill array positions by longest empty segment',
'instruction': "I need a Python program that starts with an array of n zeros and fills it with 1 through n. For each number, choose the longest contiguous segment that is still all zeros; if several have that length, choose the leftmost. Put the number in that segment's middle position, using the left of the two middle positions when its length is even. Print the final array. Input starts with t, followed by one n per test case. There are at most 10,000 cases, each n is at least 1, and the sum of all n values is at most 200,000. For n = 5, the result should be '2 4 1 3 5'.",
'chain_of_thought': "Only the chosen empty segment changes after a placement: it splits into a left remainder and a right remainder. Store pending segments by decreasing length and then increasing left endpoint, so the next retrieved segment matches both selection rules. A min-heap keyed by negative length implements this ordering. The floor of (left + right)/2 selects the required left-middle position for even lengths. Each position is filled once, giving O(N log N) time and O(N) auxiliary space per array.",
'doc': "Uses zero-based indices internally but prints the assigned values, not indices. Empty child segments are never queued, and the heap's tie-breaker consistently chooses the leftmost segment.",
'changes': ['Kept the heap-based construction while making segment lengths and tie-breakers explicit.', 'Separated array construction from batch input parsing.', 'Removed temporary variables and used descriptive names.'],
'contract_note': 'Original deterministic construction and exact unique output retained.',
'topics': ['priority queues', 'interval splitting', 'deterministic construction'],
'code': '''
from heapq import heappop, heappush
import sys
def arrange(size: int) -> list[int]:
result = [0] * size
segments = [(-size, 0, size - 1)]
for value in range(1, size + 1):
negative_length, left, right = heappop(segments)
middle = (left + right) // 2
result[middle] = value
if left < middle:
heappush(segments, (-(middle - left), left, middle - 1))
if middle < right:
heappush(segments, (-(right - middle), middle + 1, right))
return result
def main() -> None:
values = iter(map(int, sys.stdin.buffer.read().split()))
tests = next(values)
for _ in range(tests):
print(*arrange(next(values)))
if __name__ == "__main__":
main()
'''
}
]
for item in ITEMS:
p = ROOT / 'reviewed' / f'{item["index"]:05d}'
p.mkdir(parents=True, exist_ok=True)
item['code'] = textwrap.dedent(item['code']).strip() + '\n'
(p / 'solution.py').write_text(item['code'])
(p / 'annotation.json').write_text(json.dumps(item, ensure_ascii=False, indent=2))
print('Wrote', len(ITEMS), 'individually authored pilot records.')