File size: 10,229 Bytes
f01f0d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
"""

Builds a synthetic Python coding chain-of-thought dataset.



Format matches data/prepare_sft.py expectations:

    User: <coding question>

    Neo: <|begin_of_thought|> design/trace steps <|end_of_thought|>

    <|begin_of_solution|> final code / answer <|end_of_solution|>



Covers: function writing, code tracing (what does this print),

output prediction, and simple bug fixes.



Run:

    run.bat build_coding_data.py

  (or, if the venv is active:)

    python build_coding_data.py

"""

import os
import random
import sys

# Refuse to run under the broken Windows Store Python alias
# (WindowsApps\\python.exe), which can hang indefinitely on
# this machine. Always use the project venv interpreter.
if (
    "WindowsApps" in sys.executable
    or ".venv" not in sys.prefix
):
    print(
        "ERROR: this script must run with the project venv, "
        "not the Windows Store Python alias."
    )
    print("       Use:  run.bat build_coding_data.py")
    print("       or:   .venv\\Scripts\\python.exe build_coding_data.py")
    sys.exit(1)

OUTPUT_PATH = "data/neo_sft_coding.txt"

NUM_EXAMPLES = 30000

SEED = 2026

THOUGHT_START = "<|begin_of_thought|>"
THOUGHT_END = "<|end_of_thought|>"
SOLUTION_START = "<|begin_of_solution|>"
SOLUTION_END = "<|end_of_solution|>"

rng = random.Random(SEED)


def make_conversation(question, thought, solution):
    return (
        f"User: {question}\n"
        f"Neo: {THOUGHT_START}\n"
        f"{thought}\n"
        f"{THOUGHT_END}\n"
        f"{SOLUTION_START}\n"
        f"{solution}\n"
        f"{SOLUTION_END}"
    )


# ---------------------------------------------------------
# 1. Write a simple function
# ---------------------------------------------------------

FUNCTION_SPECS = [
    (
        "is_even(n)",
        "returns True if n is even, False otherwise",
        "def is_even(n):\n    return n % 2 == 0",
        "if n % 2 == 0 it is even, else odd",
    ),
    (
        "reverse_string(s)",
        "returns the string s reversed",
        "def reverse_string(s):\n    return s[::-1]",
        "s[::-1] walks the string backwards from the end",
    ),
    (
        "count_vowels(s)",
        "returns the number of vowels (a, e, i, o, u) in s",
        "def count_vowels(s):\n    vowels = 'aeiou'\n    return sum(1 for c in s.lower() if c in vowels)",
        "lowercase s then count letters in the vowel set",
    ),
    (
        "sum_list(nums)",
        "returns the sum of all numbers in the list nums",
        "def sum_list(nums):\n    return sum(nums)",
        "the built-in sum adds every element",
    ),
    (
        "is_palindrome(s)",
        "returns True if s reads the same forwards and backwards",
        "def is_palindrome(s):\n    return s == s[::-1]",
        "compare s with its reverse",
    ),
    (
        "largest(nums)",
        "returns the largest number in the list nums",
        "def largest(nums):\n    return max(nums)",
        "the built-in max selects the largest element",
    ),
    (
        "factorial(n)",
        "returns n! for a non-negative integer n",
        "def factorial(n):\n    if n <= 1:\n        return 1\n    return n * factorial(n - 1)",
        "base case n <= 1 is 1; otherwise n times factorial(n-1)",
    ),
    (
        "fibonacci(n)",
        "returns a list of the first n Fibonacci numbers starting 0, 1",
        "def fibonacci(n):\n    fib = [0, 1]\n    for _ in range(n - 2):\n        fib.append(fib[-1] + fib[-2])\n    return fib[:n]",
        "start [0, 1], each next term is the sum of the previous two",
    ),
    (
        "fizzbuzz(n)",
        "returns a list where multiples of 3 are 'Fizz', multiples of 5 are 'Buzz', both are 'FizzBuzz', else the number",
        "def fizzbuzz(n):\n    out = []\n    for i in range(1, n + 1):\n        if i % 15 == 0:\n            out.append('FizzBuzz')\n        elif i % 3 == 0:\n            out.append('Fizz')\n        elif i % 5 == 0:\n            out.append('Buzz')\n        else:\n            out.append(i)\n    return out",
        "check both (i % 15) first, then 3, then 5, in that order",
    ),
    (
        "second_largest(nums)",
        "returns the second largest distinct number in nums, or None if there is not one",
        "def second_largest(nums):\n    uniq = sorted(set(nums))\n    return uniq[-2] if len(uniq) >= 2 else None",
        "deduplicate with a set, sort, take the second from the end",
    ),
]


def write_function():
    name, spec, code, design = rng.choice(FUNCTION_SPECS)

    question = (
        f"Write a Python function {name} that {spec}."
    )

    thought = (
        f"Plan:\n"
        f"- {design}.\n"
        f"- Write the function stub and return that value.\n"
        f"- Keep it simple and readable."
    )

    return make_conversation(
        question,
        thought,
        f"Here is the function:\n\n{code}",
    )


# ---------------------------------------------------------
# 2. Code tracing - what does this print?
# ---------------------------------------------------------

def code_trace():
    kind = rng.randint(0, 2)

    if kind == 0:
        n = rng.randint(3, 6)
        code = f"total = 0\nfor i in range(1, {n + 1}):\n    total += i\nprint(total)"
        expected = sum(range(1, n + 1))
        trace = (
            f"range(1, {n + 1}) yields {list(range(1, n + 1))}.\n"
            f"Add each value: "
            f"{'+'.join(str(x) for x in range(1, n + 1))} = {expected}."
        )

    elif kind == 1:
        n = rng.randint(2, 5)
        code = f"x = {n}\nfor i in range(3):\n    x *= 2\nprint(x)"
        expected = n * 2 ** 3
        trace = (
            f"Start with x = {n}.\n"
            f"The loop doubles x three times: "
            f"{n} -> {n * 2} -> {n * 4} -> {expected}."
        )

    else:
        a = rng.randint(2, 8)
        code = f"a = {a}\ndef add(b):\n    return a + b\nprint(add(3))"
        expected = a + 3
        trace = (
            f"a is defined at module level as {a}.\n"
            f"add(3) returns a + 3 = {a} + 3 = {expected}."
        )

    return make_conversation(
        f"What does this program print?\n\n```python\n{code}\n```",
        (
            f"Trace the program line by line.\n{trace}\n"
            f"Therefore the printed output is {expected}."
        ),
        f"The program prints:\n\n```\n{expected}\n```",
    )


# ---------------------------------------------------------
# 3. Predict the result of a call
# ---------------------------------------------------------

def output_prediction():
    start = rng.randint(5, 20)
    step = rng.randint(2, 5)

    result = start + 2 * step

    code = (
        f"def advance(value):\n"
        f"    return value + {step}\n\n"
        f"n = {start}\n"
        f"n = advance(n)\n"
        f"n = advance(n)\n"
        f"print(n)"
    )

    question = (
        f"What is the final value printed by this program?\n\n"
        f"```python\n{code}\n```"
    )

    thought = (
        f"advance(v) returns v + {step}.\n"
        f"n starts at {start}.\n"
        f"First call: {start} + {step} = {start + step}.\n"
        f"Second call: {start + step} + {step} = {result}."
    )

    return make_conversation(
        question,
        thought,
        f"The final value is {result}.",
    )


# ---------------------------------------------------------
# 4. Find and fix the bug
# ---------------------------------------------------------

BUGS = [
    (
        "returns the sum of a list but always returns 0",
        "def total(nums):\n    result = 0\n    for x in nums:\n        result = 0\n    return result",
        "fix: accumulate instead of resetting",
        "def total(nums):\n    result = 0\n    for x in nums:\n        result += x\n    return result",
    ),
    (
        "should return True for even numbers but always returns True",
        "def is_even(n):\n    return True",
        "fix: return the boolean of n % 2 == 0",
        "def is_even(n):\n    return n % 2 == 0",
    ),
    (
        "should count vowels but misses uppercase vowels",
        "def count_vowels(s):\n    vowels = 'aeiou'\n    return sum(1 for c in s if c in vowels)",
        "fix: compare against lowercase, like aeiou for 'Apple'",
        "def count_vowels(s):\n    vowels = 'aeiou'\n    return sum(1 for c in s.lower() if c in vowels)",
    ),
    (
        "off-by-one: should print numbers 1..n but prints 0..n-1",
        "def print_range(n):\n    for i in range(n):\n        print(i)",
        "fix: range(n) starts at 0, so use range(1, n + 1)",
        "def print_range(n):\n    for i in range(1, n + 1):\n        print(i)",
    ),
]


def fix_bug():
    symptom, buggy, fix_hint, fixed = rng.choice(BUGS)

    question = (
        f"The function below {symptom}. "
        f"Find the bug and write the corrected version.\n\n"
        f"```python\n{buggy}\n```"
    )

    thought = (
        f"Read the code carefully and check each line.\n"
        f"Problem: {fix_hint}.\n"
        f"Write the corrected function below."
    )

    return make_conversation(
        question,
        thought,
        f"Corrected version:\n\n```python\n{fixed}\n```",
    )


GENERATORS = [
    write_function,
    code_trace,
    output_prediction,
    fix_bug,
]


def main():
    conversations = []

    for index in range(NUM_EXAMPLES):

        conversations.append(
            rng.choice(GENERATORS)()
        )

        if (index + 1) % 5000 == 0:
            print(
                f"  generated {index + 1:,}/{NUM_EXAMPLES:,}",
                flush=True,
            )

    with open(
        OUTPUT_PATH,
        "w",
        encoding="utf-8",
    ) as f:

        f.write(
            "\n\n".join(conversations)
        )

        f.write("\n")

    print(
        f"Generated {len(conversations):,} coding conversations."
    )

    print(f"Saved to: {OUTPUT_PATH}")


if __name__ == "__main__":
    main()