"""Ayrıntılı çözüm + çalışan Python + farklı yöntemle doğrulama içeren 16 kayıt.""" import contextlib import hashlib import io import json import math from pathlib import Path ROOT=Path(__file__).resolve().parent CASES=[] SYSTEMS={ 'tr':'Matematik problemini varsayımlarıyla çöz. Kullanıcıya açık, sıralı ve denetlenebilir çözüm adımları sun. Python uygulamasını ver ve sonucu farklı bir yöntem veya değişmezlerle kontrol et. Kesin değerleri yaklaşık değerlerden ayır.', 'en':'Solve the mathematical problem under its stated assumptions. Present a detailed, ordered, checkable solution explanation. Provide runnable Python and verify its result using a different method or invariants. Distinguish exact and approximate values.'} def add(family,lang,problem,steps,code,oracle,expected,verification,conclusion,tolerance=1e-9): CASES.append(dict(family=family,lang=lang,problem=problem,steps=steps, code=code.strip(),oracle=oracle.strip(),expected=expected, verification=verification,conclusion=conclusion,tolerance=tolerance)) add('karisim_ve_buharlasma','tr', '''Kütlece %10 ve %30 tuz içeren iki çözeltiden toplam 20 kg, kütlece %18 tuzlu karışım hazırlanacak. Her çözeltiden kaç kg gerekir? Ardından yalnız 2 kg su buharlaşıyor; son tuz yüzdesi ne olur? Tuz kaybı yok. Ayrıntılı çözüm, Python kodu ve ayrı doğrulama ver.''',[ 'Düşük derişimli çözeltinin kütlesine x, yüksek derişimlininkine y diyelim. Başlangıçta toplam kütle x+y=20 kg olmalıdır; iki değişken de negatif olamaz.', 'Karışımdaki tuz kütlesi hedef derişimden 20×18/100=3,6 kg bulunur. Yüzdeler hacme değil kütleye uygulandığı için burada kütle denklemi kuruyoruz.', 'İki kaynaktan gelen tuzun toplamı 0,10x+0,30y=3,6’dır. Yüzdeleri doğrudan ortalamak, karıştırılan kütleler eşit değilse doğru sonuç vermez.', 'x=20−y yazıp yerine koyarız: 0,10(20−y)+0,30y=3,6. Buradan 2+0,20y=3,6, yani y=8 kg ve x=12 kg çıkar.', 'Başlangıç koşullarını kontrol edelim: 12+8=20 kg ve 12×0,10+8×0,30=1,2+2,4=3,6 kg tuz. Hedefin hem kütle hem tuz koşulu sağlanır.', 'Buharlaşan madde yalnız su olduğundan tuz kütlesi değişmez. Toplam kütle 20−2=18 kg’a iner; yeni derişimin paydası 20 değil 18 olmalıdır.', 'Son tuz oranı 3,6/18=0,20, yani %20’dir. Kontrol olarak son su miktarı 18−3,6=14,4 kg olup başlangıçtaki 16,4 kg sudan 2 kg eksiktir.', 'Kodda ondalık yuvarlama yerine Fraction kullanacağız. Ayrı doğrulayıcı, bu örnekteki tam kilogram adaylarını tarayıp aynı karışımı ve son tuz oranını bulacak.' ], '''from fractions import Fraction total = Fraction(20) low, high, target = Fraction(1, 10), Fraction(3, 10), Fraction(18, 100) y = total * (target - low) / (high - low) x = total - y salt = low * x + high * y remaining = total - 2 assert x >= 0 and y >= 0 and x + y == total assert salt == total * target assert remaining - salt == total - salt - 2 result = {"low_kg": str(x), "high_kg": str(y), "final_salt_fraction": str(salt / remaining)}''', '''from fractions import Fraction solutions = [] for low_kg in range(21): high_kg = 20 - low_kg salt = Fraction(low_kg, 10) + Fraction(3 * high_kg, 10) if salt == Fraction(18, 100) * 20: solutions.append((low_kg, high_kg, salt)) assert len(solutions) == 1 x, y, salt = solutions[0] result = {"low_kg": str(x), "high_kg": str(y), "final_salt_fraction": str(salt / 18)}''', {'low_kg':'12','high_kg':'8','final_salt_fraction':'1/5'}, 'Denklem çözümü ile aday taraması aynı sonucu verir. Aday taraması tek başına tüm gerçek sayılar üzerinde tekliği kanıtlamaz; tekliği sağlayan, katsayıları farklı olan iki doğrusal denklemdir. Ayrıca başlangıç/son kütle ve tuzun korunması kodda kontrol edilir.', '%10’luk çözeltiden 12 kg, %30’luk çözeltiden 8 kg alınır. Su kaybından sonra derişim %20 olur.') add('kosullu_olasilik_sirasiz_degildir','tr', '''Bir torbada kimlikleri farklı 4 kırmızı ve 3 mavi top var. Geri koymadan, sırayla iki top eş olasılıklı seçiliyor. En az bir topun mavi olduğu biliniyorsa ilk topun kırmızı olma olasılığı nedir? Ayrıntılı çözüm, Python ve örnek uzayı sayarak doğrulama ver.''',[ 'A olayını “ilk top kırmızı”, B olayını “en az bir top mavi” olarak tanımlayalım. İstenen P(A|B)=P(A∩B)/P(B)’dir; koşul örnek uzayını daraltır.', 'Topların kimlikleri farklı ve seçim sıralı olduğundan toplam 7×6=42 eş olasılıklı sonuç vardır. İlk ve ikinci topun yerini değiştirerek aynı sonuç sayamayız.', 'B’nin tümleyeni iki topun da kırmızı olmasıdır. Böyle 4×3=12 sıralı sonuç vardır; dolayısıyla B’yi sağlayan sonuç sayısı 42−12=30’dur.', 'A∩B için ilk top kırmızıysa en az bir maviyi sağlamak üzere ikinci top mavi olmalıdır. Bu durumda 4×3=12 sonuç vardır.', 'Koşullu olasılık 12/30=2/5’tir. Pay ile payda aynı, koşulu sağlayan sıralı sonuç uzayında sayıldığı için oran geçerlidir.', 'Olasılık çarpımlarıyla da P(B)=1−(4/7)(3/6)=5/7 ve P(A∩B)=(4/7)(3/6)=2/7 bulunur. Bölüm yine 2/5’tir.', 'Koşulsuz ilk-kırmızı olasılığı 4/7’dir; onu doğrudan cevap vermek B koşulunu yok sayardı. En az bir mavi bilgisi ilk rengin dağılımını değiştirir.', 'Ana kod kesin kesir hesabını, doğrulayıcı ise farklı kimlikli topların bütün sıralı ikililerini kullanacak. Böylece formüldeki olay tanımları sayımla sınanır.' ], '''from fractions import Fraction p_b = 1 - Fraction(4, 7) * Fraction(3, 6) p_a_and_b = Fraction(4, 7) * Fraction(3, 6) answer = p_a_and_b / p_b assert 0 <= answer <= 1 result = {"conditional_probability": str(answer), "eligible_pairs": 30, "favourable_pairs": 12}''', '''from fractions import Fraction from itertools import permutations balls = [("R", i) for i in range(4)] + [("B", i) for i in range(3)] pairs = list(permutations(balls, 2)) eligible = [p for p in pairs if any(ball[0] == "B" for ball in p)] favourable = [p for p in eligible if p[0][0] == "R"] assert len(pairs) == 42 result = {"conditional_probability": str(Fraction(len(favourable), len(eligible))), "eligible_pairs": len(eligible), "favourable_pairs": len(favourable)}''', {'conditional_probability':'2/5','eligible_pairs':30,'favourable_pairs':12}, 'Doğrulayıcı tekrar seçimi yasak olan kimlikli topları permütasyonla sayar. 42 toplam, 30 koşula uygun ve 12 elverişli sonuç bulması hem payı hem paydayı kontrol eder. Bu tam sayım, bu küçük örnek uzayında Monte Carlo tahmini değildir.', 'İstenen koşullu olasılık tam olarak 2/5, yani %40’tır.') add('sifir_bir_sirt_cantasi','tr', '''Kapasitesi 10 kg olan çantada beş farklı eşyanın her biri en fazla bir kez alınabilir. (Ağırlık, değer) çiftleri A=(2,3), B=(3,4), C=(4,5), D=(5,8), E=(9,10). Değeri en büyük seçimi bul; dinamik programlama kodu yaz ve tüm alt kümelerle doğrula.''',[ 'Her eşya için alınır/alınmaz kararı vardır; bu 0/1 çanta problemidir. Kapasiteyi aşmadan değer toplamını en büyük yapmak istiyoruz; kesirli eşya almaya izin yok.', 'E alınırsa 9 kg kullanılır. Kalan 1 kg’a başka hiçbir eşya sığmadığından toplam değer yalnız 10 olur; E içeren bütün seçenekler bu değeri aşamaz.', 'E alınmazsa A,B,C,D birlikte 14 kg ve 20 değer eder. 10 kg’a inmek için en az 4 kg ağırlık çıkarılmalıdır.', 'C’yi çıkarmak 4 kg ve 5 değer kaybettirir; A+B+D seçimi 10 kg ve 15 değer verir. 5’ten az değer kaybeden çıkarmalar yalnız A veya B’dir ve yeterli ağırlığı çıkarmaz.', 'Bu nedenle E’siz durumda 15 değerden fazlası mümkün değildir. E’li en iyi 10 olduğundan A+B+D genel optimumdur. Bu kısa üst sınır, kod sonucunu açıklayan bir kanıttır.', 'Dinamik programlamada dp[i][c], ilk i eşya ve c kapasite için en iyi değerdir. Ya i’inci eşya alınmaz ya da sığıyorsa önceki satırdan kalan kapasiteye eklenir.', 'Önceki satırı kullanmak önemlidir: aynı eşyayı birden çok kez seçmeye izin vermez. Son tablodan geriye giderek hangi eşyanın optimuma katkı verdiğini çıkarabiliriz.', 'Doğrulayıcı 2⁵=32 alt kümeyi bağımsız olarak değerlendirecek. Yalnız optimum değeri değil, bu örnekte en iyi eşya kümesinin tekliğini de kontrol edeceğiz.' ], '''items = [("A", 2, 3), ("B", 3, 4), ("C", 4, 5), ("D", 5, 8), ("E", 9, 10)] capacity = 10 dp = [[0] * (capacity + 1) for _ in range(len(items) + 1)] for i, (_, weight, value) in enumerate(items, 1): for c in range(capacity + 1): dp[i][c] = dp[i - 1][c] if weight <= c: dp[i][c] = max(dp[i][c], dp[i - 1][c - weight] + value) c, chosen = capacity, [] for i in range(len(items), 0, -1): if dp[i][c] != dp[i - 1][c]: name, weight, _ = items[i - 1] chosen.append(name) c -= weight chosen.reverse() weight = sum(w for name, w, _ in items if name in chosen) assert weight <= capacity result = {"items": chosen, "weight": weight, "value": dp[-1][capacity]}''', '''from itertools import combinations items = [("A", 2, 3), ("B", 3, 4), ("C", 4, 5), ("D", 5, 8), ("E", 9, 10)] feasible = [] for size in range(6): for subset in combinations(items, size): weight = sum(x[1] for x in subset) value = sum(x[2] for x in subset) if weight <= 10: feasible.append(([x[0] for x in subset], weight, value)) best_value = max(x[2] for x in feasible) best = [x for x in feasible if x[2] == best_value] assert len(best) == 1 names, weight, value = best[0] result = {"items": names, "weight": weight, "value": value}''', {'items':['A','B','D'],'weight':10,'value':15}, 'Tablo yöntemi ile alt küme taraması aynı seçimi bulur. Ek olarak elle kurulan değer kaybı sınırı 15’in yalnız iyi bir aday değil optimum olduğunu gösterir. Bu küçük örnekte tam tarama uygundur; büyük eşya sayısında 2ⁿ maliyeti hızla büyür.', 'A, B ve D alınır: toplam ağırlık 10 kg, toplam değer 15.') add('moduler_kosullar_ve_alt_sinir','tr', '''Bir n tam sayısı 5’e bölününce 2, 7’ye bölününce 3, 9’a bölününce 4 kalanını veriyor. En küçük negatif olmayan çözümü ve bu koşulları sağlayan en küçük n≥1000 değerini bul. Yapıcı kod ve ayrı tarama doğrulaması ver.''',[ 'İlk iki koşulu birleştirelim. n=2+5k yazarsak mod 7’de 2+5k≡3 olur; yani 5k≡1. 5’in mod 7 tersi 3 olduğundan k≡3 ve n≡17 (mod 35).', 'Bu yüzden n=17+35t yazabiliriz. Üçüncü koşul mod 9’da 8+8t≡4, dolayısıyla 8t≡5 olur. 8’in mod 9 tersi 8’dir; t≡40≡4 bulunur.', 't=4 seçince n=17+35×4=157 çıkar. 5,7,9 ikişer ikişer aralarında asal olduğundan ortak periyot 5×7×9=315’tir.', 'Genel çözüm n=157+315q, q bir tam sayıdır. 157 bu periyotta 0 ile 314 arasında bulunduğundan en küçük negatif olmayan çözümdür.', 'n≥1000 için 157+315q≥1000, yani q≥843/315 gerekir. En küçük uygun tam sayı q=3’tür; sonuç 157+945=1102 olur.', 'Kontrol: 1102=5×220+2=7×157+3=9×122+4. Bir önceki periyottaki çözüm 787’dir ve 1000 altındadır; böylece en küçük uygunluk da kontrol edilir.', 'Ana kod, her yeni modülde önceki koşulları koruyan adım büyüklüğüyle ilerleyecek. Periyodu çarpmak yalnız bu örnekte modüller aralarında asal olduğu için doğrudur.', 'Doğrulayıcı [0,315) aralığını doğrudan tarar; ayrıca 1000’den başlayıp uygun ilk sayıyı bulur. Yapıcı birleştirme ile düz tarama farklı işlem yollarıdır.' ], '''mods = [(5, 2), (7, 3), (9, 4)] n, step = 0, 1 for modulus, remainder in mods: while n % modulus != remainder: n += step step *= modulus # Bu örnekte modüller aralarında asal. first = n q = max(0, (1000 - first + step - 1) // step) above = first + q * step assert all(above % m == r for m, r in mods) assert above >= 1000 and above - step < 1000 result = {"first": first, "period": step, "first_at_least_1000": above}''', '''conditions = lambda n: n % 5 == 2 and n % 7 == 3 and n % 9 == 4 residues = [n for n in range(315) if conditions(n)] assert len(residues) == 1 above = next(n for n in range(1000, 1315) if conditions(n)) result = {"first": residues[0], "period": 315, "first_at_least_1000": above}''', {'first':157,'period':315,'first_at_least_1000':1102}, 'İki kod da 157 ve 1102 sonuçlarını verir. Her kalanın tek tek denetlenmesi adayın uygunluğunu, bir periyottaki tekliğin taranması ve önceki çözümün 1000 altında olması ise minimum iddialarını destekler.', 'En küçük negatif olmayan çözüm 157; en küçük n≥1000 çözümü 1102’dir. Bütün çözümler 157+315q biçimindedir.') add('turevle_kutu_optimizasyonu','tr', '''36 cm × 24 cm dikdörtgen kartonun dört köşesinden kenarı x cm kareler kesilip kenarlar kaldırılarak üstü açık kutu yapılıyor. Sürekli x değişkeni için hacmi en büyük yapan kesimi ve hacmi bul. Analitik çözüm, Python ve türev kullanmayan sayısal kontrol ver.''',[ 'Kesimden sonra yükseklik x, taban kenarları 36−2x ve 24−2x olur. Pozitif boyutlu bir kutu için 0 0 result = {"cut_cm": round(x, 6), "volume_cm3": round(volume, 6)}''', '''from math import sqrt def volume(x): return x * (36 - 2 * x) * (24 - 2 * x) lo, hi = 0.0, 12.0 ratio = (sqrt(5) - 1) / 2 for _ in range(100): a = hi - ratio * (hi - lo) b = lo + ratio * (hi - lo) if volume(a) < volume(b): lo = a else: hi = b x = (lo + hi) / 2 result = {"cut_cm": round(x, 6), "volume_cm3": round(volume(x), 6)}''', {'cut_cm':4.708497,'volume_cm3':1825.296587}, 'Türevli çözüm ile türevsiz sayısal arama sonuçları 10⁻⁵ mutlak toleransla karşılaştırılır. Tam optimum kesim 10−2√7’dir; JSON’daki sayılar altı ondalığa yuvarlanmıştır. Alan sınırı, kritik nokta ve türev işareti matematiksel kapsamı belirler.', 'En iyi kesim x=10−2√7 cm ≈4,708497 cm; en büyük hacim ≈1825,296587 cm³.',1e-5) add('en_kisa_yol_ve_yol_sayisi','tr', '''Pozitif ağırlıklı yönlü grafikte kenarlar A→B:2, A→C:3, B→C:1, B→D:4, C→D:2, C→E:3, D→E:1. A’dan E’ye en kısa uzaklığı ve farklı düğüm dizileri olarak en kısa yol sayısını bul. Dijkstra kodu yaz; tüm yolları sayarak doğrula.''',[ 'Yönleri ve ağırlıkları koruyalım. Bir yolun maliyeti kenar ağırlıklarının toplamıdır; sayılacak yollar farklı düğüm dizileridir, yalnız farklı toplamlar değildir.', 'A’nın uzaklığı 0 ve ona boş yol sayısı 1’dir. A’dan sonra B’ye 2 maliyetle bir yol, C’ye doğrudan 3 maliyetle bir yol bulunur.', 'B işlenince B→C kenarı 2+1=3 verir; bu C’nin mevcut en kısa uzaklığına eşittir. Dolayısıyla C’nin uzaklığı 3 kalır, en kısa yol sayısı 2 olur.', 'B→D üzerinden uzaklık 6 adayı oluşur. C işlenince C→D ile 3+2=5 bulunur; daha kısa olduğu için D’nin eski adayı silinir ve yol sayısı C’nin iki yolundan gelir.', 'C→E kenarı 3+3=6 maliyetle iki yol üretir. D→E de 5+1=6 verir; eşit en iyi maliyete ulaştığı için iki yol daha eklenir.', 'Böylece E’nin uzaklığı 6, yol sayısı 4 olur. Yollar A-C-E, A-B-C-E, A-C-D-E ve A-B-C-D-E’dir; her birinin maliyeti 6’dır.', 'Kodda daha kısa bir aday geldiğinde yol sayısını değiştirir, eşit aday geldiğinde ekleriz. Pozitif ağırlıklar sayesinde bir en kısa yolun öncülleri ilgili düğümden daha küçük uzaklıktadır.', 'Bu grafik döngüsüzdür. Ayrı doğrulayıcı A’dan E’ye tüm yolları derinlik öncelikli aramayla çıkarır; maliyetlerin minimumunu ve bu minimumun kaç kez oluştuğunu sayar.' ], '''import heapq graph = {"A": [("B", 2), ("C", 3)], "B": [("C", 1), ("D", 4)], "C": [("D", 2), ("E", 3)], "D": [("E", 1)], "E": []} dist = {v: float("inf") for v in graph} ways = {v: 0 for v in graph} dist["A"], ways["A"] = 0, 1 queue = [(0, "A")] while queue: d, u = heapq.heappop(queue) if d != dist[u]: continue for v, weight in graph[u]: candidate = d + weight if candidate < dist[v]: dist[v], ways[v] = candidate, ways[u] heapq.heappush(queue, (candidate, v)) elif candidate == dist[v]: ways[v] += ways[u] result = {"distance": dist["E"], "shortest_path_count": ways["E"]}''', '''edges = [("A","B",2),("A","C",3),("B","C",1),("B","D",4), ("C","D",2),("C","E",3),("D","E",1)] paths = [] def visit(path, cost): if path[-1] == "E": paths.append((path, cost)) return for u, v, weight in edges: if u == path[-1] and v not in path: visit(path + [v], cost + weight) visit(["A"], 0) best = min(cost for _, cost in paths) result = {"distance": best, "shortest_path_count": sum(cost == best for _, cost in paths)}''', {'distance':6,'shortest_path_count':4}, 'Bir kod öncelik kuyruğu ve uzaklık gevşetmesi, diğeri tam yol sayımı kullanır. Eşleşme hem en kısa maliyeti hem eşit maliyetli yolların sayısını sınar. Bu yol sayma uygulaması sıfır ağırlıklı döngülere genellenmiş olarak sunulmuyor; soruda pozitif ağırlık ve döngüsüz yapı var.', 'A→E en kısa uzaklık 6; bu uzaklığı sağlayan dört farklı düğüm dizisi vardır.') add('engelli_izgara_dahil_haric','tr', '''(0,0)’dan (4,4)’e yalnız sağa veya yukarı birer birim gidiliyor. (1,1) ve (2,3) noktalarına basmak yasak. Kaç yol vardır? Dahil-hariç ile çöz, dinamik programlama yaz ve tüm hareket dizilerini tarayarak doğrula.''',[ 'Engel yokken toplam dört sağ ve dört yukarı hareket gerekir. Sekiz hareket içinde dört sağın yerini seçmek C(8,4)=70 farklı yol verir.', '(1,1)’den geçen yolları sayalım. Başlangıçtan oraya C(2,1)=2, oradan sona C(6,3)=20 yol vardır; çarpım 40’tır.', '(2,3)’ten geçen yollar için başlangıçtan C(5,2)=10, sona kalan iki sağ ve bir yukarı hareket için C(3,2)=3 seçenek vardır; toplam 30’dur.', '70−40−30 yapmak iki yasak noktadan da geçen yolları iki kez çıkarır. Bu yolları bir kez geri eklemeliyiz; dahil-hariç ilkesinin düzeltme terimi budur.', 'İki noktadan geçen bir yol önce (1,1)’e, sonra (2,3)’e uğrar; ters sıra yalnız sağ/yukarı hareketle mümkün değildir. Sayı 2×C(3,1)×3=18’dir.', 'Yasaklardan kaçınan yol sayısı 70−40−30+18=18 olur. Geri eklenen 18, cevapla tesadüfen aynı sayıdır; iki terimin anlamı farklıdır.', 'Dinamik programlamada engel hücreler 0 alır. Diğer bir noktanın yol sayısı sol komşudan ve alt komşudan gelen yolların toplamıdır; başlangıç 1’dir.', 'Tam tarama doğrulayıcısı sekiz adımın dört sağ konumunu seçer. Her hareketten sonra noktayı kontrol edip bir engele değen diziyi reddeder; böylece ara noktalar da denetlenir.' ], '''blocked = {(1, 1), (2, 3)} dp = [[0] * 5 for _ in range(5)] for x in range(5): for y in range(5): if (x, y) in blocked: continue if (x, y) == (0, 0): dp[x][y] = 1 else: dp[x][y] = (dp[x-1][y] if x else 0) + (dp[x][y-1] if y else 0) assert dp[1][1] == 0 and dp[2][3] == 0 result = {"valid_paths": dp[4][4]}''', '''from itertools import combinations blocked = {(1, 1), (2, 3)} count = 0 for right_positions in combinations(range(8), 4): right_positions = set(right_positions) x = y = 0 valid = True for step in range(8): if step in right_positions: x += 1 else: y += 1 if (x, y) in blocked: valid = False break if valid: assert (x, y) == (4, 4) count += 1 result = {"valid_paths": count}''', {'valid_paths':18}, 'Üç farklı bakış aynı sayıyı üretir: dahil-hariç hesabı, hücre tabanlı dinamik programlama ve hareket dizilerinin tam taraması. Doğrulayıcı yalnız hedefte engel aramaz; her ara konumu kontrol eder. Bu, engelden geçip sona ulaşan hatalı dizileri saymayı önler.', 'İki yasak noktaya basmayan 18 yol vardır.') add('polinom_ve_toplam','tr', '''Derecesi en fazla iki olan bir polinom için f(0)=2, f(1)=5, f(2)=10. Polinomu, f(10)’u ve f(1)+...+f(10) toplamını bul. Katsayıları kodla çıkar ve sonlu farklarla bağımsız kontrol et.''',[ 'Derece koşulu nedeniyle f(n)=an²+bn+c yazabiliriz. Bu koşul önemli: yalnız üç değer, keyfi bir fonksiyonun sonraki değerlerini tek başına belirlemez.', 'n=0 için c=2’dir. n=1 için a+b+2=5, yani a+b=3 olur. n=2 için 4a+2b+2=10, yani 2a+b=4 elde edilir.', 'İkinci katsayı denkleminden ilkini çıkarınca a=1, ardından b=2 bulunur. Dolayısıyla f(n)=n²+2n+2’dir.', 'Verilen üç noktayı yerine koyup denetleyelim: 2, 1+2+2=5 ve 4+4+2=10 çıkar. Katsayıların üç veriyi de sağlaması gerekir.', 'f(10)=100+20+2=122. Toplam için Σn²=385, Σn=55 ve on tane sabit 2 terimi 20 verir; sonuç 385+110+20=515’tir.', 'Sonlu farklar ayrı bir kontrol sağlar: 2,5,10 değerlerinin birinci farkları 3 ve 5, ikinci farkı 2’dir. Kuadratik polinomda ikinci fark sabit kalır.', 'Doğrulayıcı sonraki değerleri, birinci farkı her adımda 2 artırarak oluşturacak. n=1’den n=10’a kadar değerleri toplar; n=0 terimini yanlışlıkla dahil etmez.', 'Ana kod katsayıları Fraction ile çıkarır ve polinomu doğrudan değerlendirir. Fark tablosu yöntemi aynı kapalı biçimi çağırmadan f(10) ve toplamı yeniden hesaplar.' ], '''from fractions import Fraction f0, f1, f2 = map(Fraction, (2, 5, 10)) c = f0 a = (f2 - 2 * f1 + f0) / 2 b = f1 - a - c def f(n): return a * n * n + b * n + c assert [f(n) for n in range(3)] == [f0, f1, f2] result = {"coefficients": [str(a), str(b), str(c)], "f10": str(f(10)), "sum_1_to_10": str(sum(f(n) for n in range(1, 11)))}''', '''from fractions import Fraction value, difference, second_difference = 2, 3, 2 c = value a = Fraction(second_difference, 2) b = Fraction(difference) - a values = [] for n in range(1, 11): value += difference values.append(value) difference += second_difference assert values[:2] == [5, 10] result = {"coefficients": [str(a), str(b), str(c)], "f10": str(values[-1]), "sum_1_to_10": str(sum(values))}''', {'coefficients':['1','2','2'],'f10':'122','sum_1_to_10':'515'}, 'Kapalı polinom ve sabit ikinci farklarla üretim aynı katsayıları, değeri ve toplamı verir. İkinci yöntemde a ikinci farkın yarısı, b ilk farktan a çıkarılarak bulunur. Polinomun tekliği derece≤2 varsayımı ve üç farklı girdi noktasına dayanır.', 'f(n)=n²+2n+2, f(10)=122 ve f(1)+...+f(10)=515.') add('integer_production_with_optimality_bound','en', '''A toy factory makes nonnegative integer quantities x and y. Capacity constraints are 2x+y≤14 and x+3y≤18. Profit is 5x+7y. Find an optimal plan, prove optimality rather than only finding a feasible plan, implement the search, and verify it with exhaustive enumeration.''',[ 'The variables count whole products, so fractional quantities are not allowed. The objective is to maximise 5x+7y over nonnegative integer pairs satisfying both capacities.', 'First derive a bound that applies to every feasible plan. Multiply the first inequality by 8/5 and the second by 9/5; both multipliers are nonnegative, so the inequality directions stay unchanged.', 'The left side becomes 5x+7y. The right side is (8×14+9×18)/5=274/5=54.8. Since profit is an integer, every feasible integer plan has profit at most 54.', 'Now rule out 54. If 5x+7y=54, reduction modulo 5 gives 2y≡4, so y≡2 modulo 5. The second capacity implies y≤6; therefore the only candidate is y=2.', 'That candidate requires x=8, but then 2x+y=18>14. Profit 54 is impossible. Consequently any feasible plan has profit at most 53.', 'The plan x=5, y=4 is feasible: 2×5+4=14 and 5+3×4=17≤18. Its profit is 25+28=53, meeting the tightened bound and proving optimality.', 'For implementation, enumerate y from 0 to 6. At each y, the largest feasible x is the smaller of floor((14−y)/2) and 18−3y; profit increases with x for fixed y.', 'The verifier will instead enumerate all bounded x,y pairs and filter both constraints. Agreement checks the search, while the weighted bound plus exclusion of 54 explains why no unseen feasible plan can do better.' ], '''from fractions import Fraction candidates = [] for y in range(7): x = min((14 - y) // 2, 18 - 3 * y) if x >= 0: assert 2 * x + y <= 14 and x + 3 * y <= 18 candidates.append((5 * x + 7 * y, x, y)) profit, x, y = max(candidates) assert Fraction(profit) <= Fraction(274, 5) result = {"x": x, "y": y, "profit": profit}''', '''feasible = [] for x in range(8): for y in range(7): if 2 * x + y <= 14 and x + 3 * y <= 18: feasible.append((5 * x + 7 * y, x, y)) best = max(p for p, _, _ in feasible) winners = [(x, y) for p, x, y in feasible if p == best] assert winners == [(5, 4)] x, y = winners[0] result = {"x": x, "y": y, "profit": best}''', {'x':5,'y':4,'profit':53}, 'The optimised one-dimensional search and the full rectangular enumeration produce the same unique plan. The mathematical bound is stronger than a mere test: it limits all feasible real plans to 54.8 and all integer plans to at most 53 after excluding 54.', 'Produce x=5 and y=4 for maximum profit 53.') add('bayes_factory_two_positive_tests','en', '''In a hypothetical factory, 2% of parts are defective. A test is positive on 95% of defective parts and on 10% of nondefective parts. Find the probability of a defect after one positive test and after two positives. Assume repeated test outcomes are independent conditional on defect status. Use exact fractions and a separate population-count verification.''',[ 'Let D denote a defective part and + a positive result. The supplied rates are P(D)=1/50, P(+|D)=19/20, and P(+|not D)=1/10. A positive test does not itself mean a 95% chance of defect.', 'For one positive, the defective contribution is (1/50)(19/20)=19/1000. The nondefective contribution is (49/50)(1/10)=98/1000; both can produce positives.', 'Total positive probability is 117/1000. Bayes’ rule therefore gives P(D|+)=19/117, approximately 16.2393%. The relatively large nondefective population matters.', 'For two positive results, conditional independence allows squaring the positive rates within each status group. It does not mean that the unconditional test outcomes are independent.', 'The two-positive defective contribution is (1/50)(19/20)²=361/20000. The nondefective contribution is (49/50)(1/10)²=196/20000.', 'Their sum is 557/20000, so P(D|+,+)=361/557, approximately 64.8115%. The second positive raises the posterior under the stated model, but does not make it 100%.', 'For a count-based check, use a hypothetical population of 1,000,000 parts. It contains 20,000 defective and 980,000 nondefective parts; all listed subgroup counts are integral.', 'Among those parts, one-positive counts are 19,000 and 98,000; two-positive counts are 18,050 and 9,800. These are exact model allocations for checking the arithmetic, not measurements from a real factory.' ], '''from fractions import Fraction prior = Fraction(1, 50) sensitivity = Fraction(19, 20) false_positive = Fraction(1, 10) def posterior(positives): good_evidence = prior * sensitivity ** positives other_evidence = (1 - prior) * false_positive ** positives return good_evidence / (good_evidence + other_evidence) one, two = posterior(1), posterior(2) assert 0 < one < two < 1 result = {"one_positive": str(one), "two_positives": str(two)}''', '''from fractions import Fraction defective, nondefective = 20000, 980000 one_defective = defective * 95 // 100 one_nondefective = nondefective * 10 // 100 two_defective = one_defective * 95 // 100 two_nondefective = one_nondefective * 10 // 100 assert (one_defective, one_nondefective) == (19000, 98000) assert (two_defective, two_nondefective) == (18050, 9800) result = {"one_positive": str(Fraction(one_defective, one_defective + one_nondefective)), "two_positives": str(Fraction(two_defective, two_defective + two_nondefective))}''', {'one_positive':'19/117','two_positives':'361/557'}, 'The formula implementation and integer subgroup counts agree exactly. The count divisions happen to be integral at the chosen population size; they are not a general licence to truncate probabilities. If conditional independence fails, the two-positive calculation must be revised.', 'One positive: 19/117 ≈16.2393%. Two positives under conditional independence: 361/557 ≈64.8115%.') add('receipt_discount_tax_rounding','en', '''A fictional receipt has 3 items at 12.50 units and 2 items at 8.00 units. Apply a 10% discount to goods only. Shipping is 5.00 if discounted goods are below 50.00, otherwise zero. Add 8% tax on discounted goods only; round the tax to cents, half up, before adding the total. Compute every stage, code it, and verify using integer cents.''',[ 'The gross goods amount is 3×12.50+2×8.00=37.50+16.00=53.50 units. Quantity multiplication happens before applying the discount.', 'A 10% discount leaves 90% of the goods amount: 53.50×0.90=48.15. The discount amount is 5.35; shipping is not discounted.', 'The shipping threshold uses discounted goods, not the gross amount and not the final receipt. Because 48.15<50.00, shipping is 5.00.', 'The taxable base is also discounted goods only. Raw tax is 48.15×0.08=3.852 units; shipping is explicitly excluded from this tax calculation.', 'The rule requires rounding the tax itself to cents before addition. Half-up rounding gives 3.85, because the third decimal digit is 2.', 'The total is 48.15+5.00+3.85=57.00. Applying tax to shipping or checking the shipping threshold before discount would solve a different problem.', 'The main implementation uses Decimal constructed from strings. This avoids introducing binary floating-point approximations before monetary rounding.', 'The verifier uses integer cents and Fraction for the raw tax. Adding one half before taking the floor implements half-up rounding for these nonnegative cent amounts; the rounding stage matches the problem statement.' ], '''from decimal import Decimal, ROUND_HALF_UP cent = Decimal("0.01") gross = 3 * Decimal("12.50") + 2 * Decimal("8.00") goods = (gross * Decimal("0.90")).quantize(cent, rounding=ROUND_HALF_UP) shipping = Decimal("5.00") if goods < Decimal("50.00") else Decimal("0.00") tax = (goods * Decimal("0.08")).quantize(cent, rounding=ROUND_HALF_UP) total = goods + shipping + tax assert gross - goods == Decimal("5.35") result = {"gross": str(gross), "discounted_goods": str(goods), "shipping": str(shipping), "tax": str(tax), "total": str(total)}''', '''from fractions import Fraction gross_cents = 3 * 1250 + 2 * 800 goods_cents = gross_cents * 9 // 10 assert gross_cents * 9 % 10 == 0 shipping_cents = 500 if goods_cents < 5000 else 0 raw_tax_cents = Fraction(goods_cents * 8, 100) rounded = raw_tax_cents + Fraction(1, 2) tax_cents = rounded.numerator // rounded.denominator def money(cents): return f"{cents // 100}.{cents % 100:02d}" result = {"gross": money(gross_cents), "discounted_goods": money(goods_cents), "shipping": money(shipping_cents), "tax": money(tax_cents), "total": money(goods_cents + shipping_cents + tax_cents)}''', {'gross':'53.50','discounted_goods':'48.15','shipping':'5.00','tax':'3.85','total':'57.00'}, 'Decimal arithmetic and exact cent arithmetic agree at every reported stage, not only at the final total. The integer discount is exact for this input; the verifier asserts divisibility instead of silently truncating a fractional cent. All tax and shipping rules are fictional task assumptions.', 'Discounted goods 48.15, shipping 5.00, rounded tax 3.85, final total 57.00 units.') add('piecewise_catch_up_with_stop','en', '''Cyclist A starts at time 0 at 12 km/h. Cyclist B starts from the same point 15 minutes later at 18 km/h. A stops from minute 25 through minute 35, then resumes at 12 km/h. When and where does B first catch A after B starts? Use a piecewise mathematical model, Python, and a second-by-second exact check.''',[ 'Use minutes from A’s start. A rides at 12/60=1/5 km per minute; B rides at 18/60=3/10 km per minute after minute 15.', 'A’s position is t/5 before minute 25, 5 km from minute 25 to 35, and t/5−2 after minute 35. The subtraction of 2 km accounts for the ten-minute stop.', 'For t≥15, B’s position is 3(t−15)/10. Solve equality separately in each A segment; a root is valid only if it lies inside that segment.', 'In the first relevant segment, t/5=3(t−15)/10 gives t=45. That is outside [15,25], so it must be rejected rather than reported as the catch time.', 'During A’s stop, 5=3(t−15)/10 gives t=95/3 minutes, or 31 minutes 40 seconds. This lies within [25,35], so it is a valid meeting.', 'After the stop, t/5−2=3(t−15)/10 gives t=25, outside the later segment. There is no valid earlier meeting after B’s departure; the first segment had none.', 'The meeting position is 5 km. The absolute time is 1900 seconds after A starts, and the elapsed time for B is 1900−900=1000 seconds, or 16 minutes 40 seconds.', 'The main code solves segment equations with Fraction. The verifier scans integer seconds using direct position formulas; this check can locate the exact meeting here because the analytically derived time is an integer number of seconds.' ], '''from fractions import Fraction as F segments = [(F(15), F(25), F(1, 5), F(0)), (F(25), F(35), F(0), F(5)), (F(35), None, F(1, 5), F(-2))] b_speed, b_offset = F(3, 10), F(-9, 2) meetings = [] for lo, hi, a_speed, a_offset in segments: t = (b_offset - a_offset) / (a_speed - b_speed) if t >= lo and (hi is None or t <= hi): meetings.append(t) t = min(meetings) seconds = t * 60 assert seconds.denominator == 1 position = b_speed * t + b_offset result = {"seconds_after_A": int(seconds), "seconds_after_B": int(seconds - 900), "distance_km": str(position)}''', '''from fractions import Fraction found = None for seconds in range(900, 3601): moving_a = min(seconds, 1500) + max(seconds - 2100, 0) a_position = Fraction(moving_a * 12, 3600) b_position = Fraction((seconds - 900) * 18, 3600) if a_position == b_position: found = (seconds, a_position) break assert found is not None t, position = found result = {"seconds_after_A": t, "seconds_after_B": t - 900, "distance_km": str(position)}''', {'seconds_after_A':1900,'seconds_after_B':1000,'distance_km':'5'}, 'The analytic segment solution and exact second grid find the same first meeting. A time grid would not prove an arbitrary non-integer-second meeting; here the closed-form result shows why the grid contains the answer. Rejecting roots outside their segment is essential.', 'B first catches A at minute 31:40 from A’s start, 16:40 after B starts, at 5 km.') add('fence_area_complete_square','en', '''A rectangular enclosure borders a straight river, so only three sides need fencing. There are 120 metres of fence. Let x be each perpendicular side and y the side parallel to the river. Find the maximum area for continuous nonnegative lengths. Prove the result without calculus, implement it, and give a finite numerical check with its limits.''',[ 'Only two sides of length x and one of length y use fence. The constraint is 2x+y=120, not 2x+2y=120. Thus y=120−2x.', 'Nonnegative lengths require 0≤x≤60. Positive area occurs in the interior; the endpoints describe degenerate enclosures with zero area.', 'Area is A(x)=xy=x(120−2x)=120x−2x². Complete the square rather than assuming equal side lengths.', 'A(x)=1800−2(x−30)². The squared term is nonnegative for every real x, so A(x)≤1800 throughout the feasible interval.', 'Equality holds exactly at x=30. Substituting into the fence constraint gives y=60; the geometry is not a square because one side does not need fencing.', 'Check the dimensions: two perpendicular sides use 2×30=60 metres, the parallel side uses 60 metres, and area is 30×60=1800 square metres.', 'The implementation computes the analytic candidate and checks the fence constraint. A second routine enumerates integer x values from 0 to 60 and finds the same maximum.', 'The finite integer search alone would not prove a continuous optimum. The completed-square inequality supplies that proof; enumeration is an additional code and arithmetic check, not a replacement for it.' ], '''from fractions import Fraction fence = Fraction(120) x = fence / 4 y = fence - 2 * x area = x * y assert 2 * x + y == fence and x >= 0 and y >= 0 result = {"x_m": str(x), "y_m": str(y), "area_m2": str(area)}''', '''candidates = [(x * (120 - 2 * x), x, 120 - 2 * x) for x in range(61)] area, x, y = max(candidates) assert sum(a == area for a, _, _ in candidates) == 1 result = {"x_m": str(x), "y_m": str(y), "area_m2": str(area)}''', {'x_m':'30','y_m':'60','area_m2':'1800'}, 'The analytic formula and integer enumeration agree. The continuous claim is justified by A(x)=1800−2(x−30)², which also establishes uniqueness. The result depends on the stated straight-river geometry and using all 120 metres for the three fenced sides.', 'Use perpendicular sides of 30 m and a parallel fenced side of 60 m; the maximum area is 1800 m².') add('three_equations_exact_linear_algebra','en', '''Solve x+y+z=6, 2x−y+z=3, and x+2y−z=2. Show elimination steps, implement exact Gaussian elimination, and verify using determinants rather than calling the same elimination routine again.''',[ 'Write the augmented rows as [1,1,1|6], [2,−1,1|3], and [1,2,−1|2]. Exact rational arithmetic avoids rounding during row operations.', 'Subtract twice the first equation from the second: −3y−z=−9. Subtract the first equation from the third: y−2z=−4. These transformations preserve the solution set.', 'The third reduced equation gives y=2z−4. Substitute into the second: −3(2z−4)−z=−9, so −7z+12=−9 and z=3.', 'Then y=2×3−4=2 and x=6−2−3=1. Substitution into every original equation gives 6, 3, and 2 respectively.', 'The coefficient determinant is 7, which is nonzero. Therefore the square linear system has a unique solution; finding a satisfying triple is not merely finding one of many candidates.', 'The main code performs Gauss–Jordan elimination: select a nonzero pivot, swap if needed, normalise the pivot row, and eliminate that column from all other rows.', 'For an independent calculation, Cramer’s rule replaces each coefficient column by the right-hand side. The replacement determinants are 7, 14, and 21; dividing by 7 yields 1, 2, and 3.', 'The determinant routine expands over permutations for this small 3×3 matrix. This is deliberately different from row elimination, and the main code also substitutes its result into the original system.' ], '''from fractions import Fraction as F A = [[1, 1, 1], [2, -1, 1], [1, 2, -1]] b = [6, 3, 2] m = [[F(value) for value in row] + [F(rhs)] for row, rhs in zip(A, b)] for col in range(3): pivot = next(r for r in range(col, 3) if m[r][col] != 0) m[col], m[pivot] = m[pivot], m[col] scale = m[col][col] m[col] = [value / scale for value in m[col]] for r in range(3): if r != col: factor = m[r][col] m[r] = [v - factor * p for v, p in zip(m[r], m[col])] solution = [m[i][-1] for i in range(3)] assert all(sum(F(a) * x for a, x in zip(row, solution)) == rhs for row, rhs in zip(A, b)) result = {"solution": [str(x) for x in solution]}''', '''from itertools import permutations from fractions import Fraction A = [[1, 1, 1], [2, -1, 1], [1, 2, -1]] b = [6, 3, 2] def det(matrix): total = 0 for p in permutations(range(3)): inversions = sum(p[i] > p[j] for i in range(3) for j in range(i + 1, 3)) term = (-1) ** inversions for i in range(3): term *= matrix[i][p[i]] total += term return total denominator = det(A) assert denominator == 7 answer = [] for col in range(3): replaced = [row[:] for row in A] for r in range(3): replaced[r][col] = b[r] answer.append(str(Fraction(det(replaced), denominator))) result = {"solution": answer}''', {'solution':['1','2','3']}, 'Exact row elimination and a permutation-based determinant method agree. Substitution checks feasibility, while the nonzero determinant checks uniqueness. Determinant expansion is reasonable for this tiny verifier but is not presented as an efficient large-system solver.', 'The unique solution is x=1, y=2, z=3.') add('digit_counting_and_conditional_probability','en', '''Choose uniformly from four-digit integers formed from digits 0,1,2,3,4,5 without repetition and without a leading zero. Find the probability of divisibility by 5. Then, conditional on divisibility by 5, find the probability that the first digit is 1. Show counts, Python, and a permutation-based verification.''',[ 'The first digit has five choices, excluding zero. After it is chosen, the remaining positions have 5, 4, and 3 choices, so the total sample space is 5×5×4×3=300 integers.', 'Divisibility by 5 requires the last digit to be 0 or 5. These cases are disjoint and must be counted with their different leading-digit restrictions.', 'If the last digit is 0, the first digit can be any of 1 through 5. The two middle positions then have 4 and 3 choices, giving 5×4×3=60.', 'If the last digit is 5, the first digit can be 1,2,3,4: four choices. The middle positions have 4 and 3 choices, giving 48. Zero is allowed in a middle position.', 'The divisible count is 60+48=108. Its probability is 108/300=9/25. Treating the two ending cases as identical would miss the leading-zero restriction.', 'Now fix the first digit to 1 as well. For ending 0, the middle positions have 4×3=12 possibilities; for ending 5, they also have 12. The intersection count is 24.', 'Conditioning restricts the denominator to the 108 divisible integers, so the second probability is 24/108=2/9, not 24/300.', 'The formula code uses these counts. The verifier constructs every length-four permutation, rejects leading zeros, evaluates the integer, and independently counts divisibility and the first-digit event.' ], '''from fractions import Fraction total = 5 * 5 * 4 * 3 ending_zero = 5 * 4 * 3 ending_five = 4 * 4 * 3 divisible = ending_zero + ending_five intersection = 4 * 3 + 4 * 3 result = {"total": total, "divisible": divisible, "p_divisible": str(Fraction(divisible, total)), "p_first_one_given_divisible": str(Fraction(intersection, divisible))}''', '''from itertools import permutations from fractions import Fraction valid, divisible, first_one = 0, 0, 0 for digits in permutations(range(6), 4): if digits[0] == 0: continue valid += 1 number = 1000 * digits[0] + 100 * digits[1] + 10 * digits[2] + digits[3] if number % 5 == 0: divisible += 1 first_one += digits[0] == 1 assert first_one == 24 result = {"total": valid, "divisible": divisible, "p_divisible": str(Fraction(divisible, valid)), "p_first_one_given_divisible": str(Fraction(first_one, divisible))}''', {'total':300,'divisible':108,'p_divisible':'9/25','p_first_one_given_divisible':'2/9'}, 'The product-rule counts and permutation enumeration agree on all reported quantities. Every generated integer is unique because the digit tuple uniquely identifies it. Uniform selection from valid integers therefore matches the equal-weight enumeration used by the verifier.', 'P(divisible by 5)=9/25. P(first digit is 1 | divisible by 5)=2/9.') add('binary_search_shipping_capacity','en', '''Packages with weights [7,2,5,10,8] must be shipped in order within two days. Packages are indivisible, each day gets a contiguous block, and every day has the same integer capacity. Find the minimum capacity. Explain the monotonic test, implement binary search, and verify using all two-block cuts.''',[ 'At least the heaviest package must fit, so capacity is at least 10. Capacity 32, the sum of all weights, is sufficient in one day; these give initial search bounds.', 'For a fixed capacity, fill each day with the longest next prefix that fits. Starting a new day only when necessary minimises the number of days for that capacity under the order constraint.', 'Feasibility is monotonic: if a capacity works, every larger capacity works using the same partition. This permits binary search over integer capacities rather than trying arbitrary guesses.', 'At capacity 21, [7,2,5] and [10,8] fit in two days. A smaller trial of 15 needs three days: [7,2,5], [10], [8]. The feasible threshold lies between them.', 'Capacity 18 works with block sums 14 and 18. Capacity 17 needs three blocks because [10,8] totals 18; after the first 14-weight block, those two packages cannot share a day.', 'The binary search maintains an interval containing the minimum feasible capacity. A feasible midpoint lowers the upper bound; an infeasible one raises the lower bound to midpoint+1.', 'When the bounds meet, the capacity is 18. The main code checks both feasibility at 18 and infeasibility at 17, directly validating the threshold.', 'For an independent check, enumerate the four possible cuts into two nonempty contiguous blocks. Their required capacities are 25,23,18,24; the minimum is 18. A one-day plan needs 32, so allowing at most two days changes nothing.' ], '''weights = [7, 2, 5, 10, 8] def days_needed(capacity): days, load = 1, 0 for weight in weights: if weight > capacity: return len(weights) + 1 if load + weight > capacity: days += 1 load = 0 load += weight return days lo, hi = max(weights), sum(weights) while lo < hi: mid = (lo + hi) // 2 if days_needed(mid) <= 2: hi = mid else: lo = mid + 1 assert days_needed(lo) <= 2 and days_needed(lo - 1) > 2 result = {"capacity": lo, "days_at_capacity": days_needed(lo)}''', '''weights = [7, 2, 5, 10, 8] cuts = [] for cut in range(1, len(weights)): cuts.append(max(sum(weights[:cut]), sum(weights[cut:]))) assert cuts == [25, 23, 18, 24] best = min(min(cuts), sum(weights)) result = {"capacity": best, "days_at_capacity": 2}''', {'capacity':18,'days_at_capacity':2}, 'Binary search with a greedy feasibility test agrees with exhaustive two-block partitioning. The verifier’s two-day count is justified because capacity 18 cannot hold the total weight 32 in one day. The monotonic property and fixed package order are prerequisites of this algorithm.', 'The minimum daily capacity is 18, using blocks [7,2,5] and [10,8].') def same_result(actual,expected,tolerance): if isinstance(expected,dict): return isinstance(actual,dict) and set(actual)==set(expected) and all(same_result(actual[k],v,tolerance) for k,v in expected.items()) if isinstance(expected,list): return isinstance(actual,list) and len(actual)==len(expected) and all(same_result(a,b,tolerance) for a,b in zip(actual,expected)) if type(expected) is float: return type(actual) in (int,float) and math.isclose(actual,expected,rel_tol=0,abs_tol=tolerance) return type(actual) is type(expected) and actual==expected def complete_code(body): return body+'\nimport json\nprint(json.dumps(result, ensure_ascii=False, sort_keys=True))\n' def execute(code): # Yalnız bu dosyada yazılmış, sabit standart-kütüphane kodu çalıştırılır. # Dış veri seti veya kullanıcıdan alınmış keyfi kod yürütülmez. output=io.StringIO() namespace={'__name__':'__dataset_example__'} with contextlib.redirect_stdout(output): exec(compile(code,'','exec'),namespace) text=output.getvalue().strip() return json.loads(text),text def format_answer(case,main_code,oracle_code,main_output,oracle_output): if case['lang']=='tr': names=['Matematiksel çözüm','Python uygulaması','Farklı yöntemle doğrulama','Sonuç'] output_label='Kodun çıktısı' verification_label='Doğrulama kodunun çıktısı' else: names=['Mathematical solution','Python implementation','Verification by a different method','Final result'] output_label='Code output' verification_label='Verifier output' steps='\n\n'.join(f'{i}. {text}' for i,text in enumerate(case['steps'],1)) return (f'### 1. {names[0]}\n\n{steps}\n\n' f'### 2. {names[1]}\n\n```python\n{main_code}```\n\n' f'{output_label}:\n\n```json\n{main_output}\n```\n\n' f'### 3. {names[2]}\n\n{case["verification"]}\n\n' f'```python\n{oracle_code}```\n\n' f'{verification_label}:\n\n```json\n{oracle_output}\n```\n\n' f'### 4. {names[3]}\n\n{case["conclusion"]}') def main(): from jinja2.sandbox import ImmutableSandboxedEnvironment assert len(CASES)==16 and len({c['family'] for c in CASES})==16 assert [c['lang'] for c in CASES].count('tr')==8 assert [c['lang'] for c in CASES].count('en')==8 rows,checks=[],[] (ROOT/'code').mkdir(exist_ok=True) for i,case in enumerate(CASES,1): assert len(case['steps'])==8 main_code,oracle_code=complete_code(case['code']),complete_code(case['oracle']) actual,main_output=execute(main_code) oracle,oracle_output=execute(oracle_code) assert same_result(actual,case['expected'],case['tolerance']),(case['family'],'main',actual) assert same_result(oracle,case['expected'],case['tolerance']),(case['family'],'verifier',oracle) assert same_result(actual,oracle,case['tolerance']),(case['family'],'comparison') record_id=f'math_code_{i:03d}' (ROOT/'code'/f'{record_id}_solution.py').write_text(main_code) (ROOT/'code'/f'{record_id}_verify.py').write_text(oracle_code) answer=format_answer(case,main_code,oracle_code,main_output,oracle_output) prompt=case['problem']+ ('\n\nSekiz açık çözüm adımı, çalıştırılabilir Python, farklı yöntemle doğrulama ve son sonucu göster.' if case['lang']=='tr' else '\n\nProvide eight explicit solution steps, runnable Python, a different-method verification, and the final result.') split='validation' if i in (5,10) else 'test' if i in (7,12) else 'train' row={'id':record_id,'messages':[{'role':'system','content':SYSTEMS[case['lang']]}, {'role':'user','content':prompt}, {'role':'assistant','content':answer}], 'metadata':{'family':case['family'],'language':case['lang'],'split':split, 'provenance':'assistant_authored_original', 'explanation_type':'public_step_by_step_solution_not_private_internal_monologue', 'step_count':len(case['steps']),'expected_result':case['expected'], 'absolute_tolerance':case['tolerance'], 'solution_code_sha256':hashlib.sha256(main_code.encode()).hexdigest(), 'verification_code_sha256':hashlib.sha256(oracle_code.encode()).hexdigest(), 'verification':'both_codes_executed_and_compared_to_reference', 'prose_independently_verified':False}} rows.append(row) checks.append({'id':record_id,'family':case['family'],'solution_passed':True,'verifier_passed':True, 'outputs_match':True,'result':actual,'verifier_result':oracle, 'absolute_tolerance':case['tolerance']}) splits={s:[r for r in rows if r['metadata']['split']==s] for s in ['train','validation','test']} template=(ROOT/'tokenizer'/'base_chat_template.jinja').read_text() env=ImmutableSandboxedEnvironment(trim_blocks=True,lstrip_blocks=True) env.globals['raise_exception']=lambda msg:(_ for _ in ()).throw(ValueError(msg)) renderer=env.from_string(template) (ROOT/'rendered').mkdir(exist_ok=True) hashes={} for split,group in splits.items(): hashes[split]=set() with (ROOT/f'{split}.jsonl').open('w') as raw,(ROOT/'rendered'/f'{split}.jsonl').open('w') as rendered: for row in group: raw.write(json.dumps(row,ensure_ascii=False)+'\n') text=renderer.render(messages=row['messages'],add_generation_prompt=False,enable_thinking=False) assert text.startswith('<|im_start|>system\n') and text.endswith('<|im_end|>\n') assert text.count('<|im_start|>')==3 rendered.write(json.dumps({'id':row['id'],'text':text},ensure_ascii=False)+'\n') hashes[split].add(hashlib.sha256(json.dumps(row['messages'][1:],ensure_ascii=False).encode()).hexdigest()) overlaps={a+'__'+b:len(hashes[a]&hashes[b]) for a,b in [('train','validation'),('train','test'),('validation','test')]} assert not any(overlaps.values()) (ROOT/'dataset.jsonl').write_text(''.join(json.dumps(row,ensure_ascii=False)+'\n' for row in rows)) (ROOT/'samples.json').write_text(json.dumps(rows,ensure_ascii=False,indent=2)+'\n') lengths=[len(row['messages'][-1]['content']) for row in rows] words=[len(row['messages'][-1]['content'].split()) for row in rows] report={'total':len(rows),'language_counts':{'tr':8,'en':8}, 'split_counts':{s:len(g) for s,g in splits.items()}, 'solution_codes_executed':16,'verification_codes_executed':16, 'all_code_outputs_match_references':True,'all_main_verifier_outputs_match':True, 'solution_steps_per_record':8,'assistant_character_lengths':{'min':min(lengths),'max':max(lengths),'mean':round(sum(lengths)/len(lengths),1)}, 'whitespace_word_counts_including_code':{'min':min(words),'max':max(words),'mean':round(sum(words)/len(words),1)}, 'exact_overlap_excluding_system':overlaps, 'template_source':'Qwen/Qwen3-0.6B-Base', 'template_revision':'da87bfb608c14b7cf20ba1ce41287e8de496c0cd', 'template_sha256':hashlib.sha256(template.encode()).hexdigest(), 'all_rendered_boundaries_checked':True,'tokenization_verified':False, 'independent_human_review':False,'prose_independently_verified':False, 'same_author_for_solution_and_verifier':True,'semantic_dedup':False,'model_improvement_measured':False, 'checks':checks} (ROOT/'validation_report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n') (ROOT/'preview_tr.md').write_text(rows[0]['messages'][-1]['content']+'\n') (ROOT/'preview_en.md').write_text(rows[8]['messages'][-1]['content']+'\n') print(json.dumps({k:v for k,v in report.items() if k!='checks'},ensure_ascii=False,indent=2)) if __name__=='__main__':main()