Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
4238 lines (4033 loc) · 329 KB
/
Copy pathindex.html
File metadata and controls
4238 lines (4033 loc) · 329 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html><html><head><meta charset=utf8><meta name=viewport content="width=device-width,initial-scale=1,viewport-fit=cover"><style>:root{color-scheme:light;box-sizing:border-box;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}html{scroll-padding-top:env(safe-area-inset-top,0px)}body{margin:0;padding:0;font:14px -apple-system,BlinkMacSystemFont,sans-serif;background:#fff;color:#000}img{max-width:100%}[hidden]:not([hidden=until-found i]){display:none!important}</style></head><body>
<!doctype html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Visualized Python Code</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&family=Monoton&family=Schibsted+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
/* ---------- Theme tokens (same as Visualized SQL Queries) ---------- */
:root{
--bg:#EDF1F6; --panel:#FFFFFF; --ink:#172033; --muted:#5B6679; --line:#D6DDE7; --chip:#F3F5F9;
--commit:#3B5BDB; --green:#2B8A3E; --green-soft:#E6F4EA; --amber:#B25E09; --amber-soft:#FFF1DE; --red:#C9372F; --red-soft:#FDECEA;
--term-bg:#182235; --title:#D97757; --accent-grad:var(--commit);
--sans:'Schibsted Grotesk', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--mono:'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--gap:8px;
box-sizing:border-box;
padding-top:env(safe-area-inset-top,0px); padding-bottom:env(safe-area-inset-bottom,0px);
}
:root[data-theme="dark"]{
--bg:#0B0C1F; --panel:#16173A; --ink:#E1E4FF; --muted:#9B9DCC; --line:#2B2D5E; --chip:#1E2049;
--commit:#8B8CF5; --green:#5FD99A; --green-soft:#14302D; --amber:#FFB86B; --amber-soft:#3A2818;
--term-bg:#06071A; --accent-grad:linear-gradient(135deg,#A193F7,#6366F1); color-scheme:dark;
}
*,*::before,*::after{box-sizing:border-box}
html{height:100%;scroll-padding-top:env(safe-area-inset-top,0px)}
body{margin:0;height:100%;background:var(--bg);color:var(--ink);font-family:var(--sans);-webkit-font-smoothing:antialiased;overflow:hidden}
:root[data-theme="dark"] body{background-image:radial-gradient(circle at 0% 0%,rgba(99,102,241,.22),transparent 38%),radial-gradient(circle at 100% 100%,rgba(99,102,241,.14),transparent 42%);background-attachment:fixed}
button{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--commit);outline-offset:2px}
.app{height:100%;padding:1vh 1vw;display:grid;grid-template-rows:auto 1fr auto;gap:var(--gap)}
footer{text-align:center;font-size:12.5px;color:var(--muted);padding:2px 0 0}
footer a{color:var(--title);font-weight:700;text-decoration:none}
footer a:hover{text-decoration:underline;text-underline-offset:3px}
header{display:grid;grid-template-columns:auto 1fr auto auto;align-items:center;column-gap:18px;min-height:46px}
.brand{grid-column:1;justify-self:start;font-family:'Monoton','Schibsted Grotesk',system-ui,sans-serif;font-size:clamp(1.6rem,2.4vw,2.1rem);font-weight:400;line-height:1;letter-spacing:.02em;color:#1B2A5B;user-select:none}
:root[data-theme="dark"] .brand{color:#FF8A3D}
h1{grid-column:2;margin:0;text-align:left;color:var(--title);font-size:clamp(1.2rem,2.2vw,1.9rem);font-weight:700;letter-spacing:-.025em;line-height:1}
.theme-btn{grid-column:4;justify-self:end;width:38px;height:38px;border-radius:50%;border:1px solid var(--line);background:var(--panel);color:var(--ink);cursor:pointer;display:grid;place-items:center;transition:background .3s,border-color .3s,transform .2s}
.theme-btn:hover{transform:scale(1.06)}
.theme-btn svg{width:18px;height:18px}
:root[data-theme="dark"] .theme-btn{background:var(--accent-grad);border-color:rgba(255,255,255,.25);color:#fff;box-shadow:0 0 0 4px rgba(139,140,245,.15)}
.main{display:grid;grid-template-columns:15fr 85fr;gap:var(--gap);min-height:0}
.body{display:grid;grid-template-columns:40fr 45fr 15fr;grid-template-rows:1fr 1fr;gap:var(--gap);min-height:0;min-width:0}
.query{grid-area:1/1}
.output{grid-area:2/1}
.memory{grid-area:1/2}
.fields{grid-area:1/3}
.interview{grid-area:2/2}
.callouts{grid-area:2/3}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;display:flex;flex-direction:column;min-height:0;min-width:0;overflow:hidden}
.panel-head{display:flex;align-items:center;gap:8px;padding:8px 12px;border-bottom:1px solid var(--line);font-size:13.5px;font-weight:600;flex:none;min-height:40px}
.panel-head .hint{margin-left:auto;font-weight:400;color:var(--muted);font-size:12.5px}
.panel-body{flex:1;min-height:0;overflow:auto;scrollbar-width:thin}
/* Sidebar */
.side nav{padding:6px}
.cat+.cat{margin-top:6px}
.sec{width:100%;display:flex;align-items:center;gap:8px;text-align:left;border:0;cursor:pointer;padding:7px 10px;border-radius:8px;background:var(--term-bg);color:#8793A8;font-size:12px;line-height:1.3}
.sec-text{flex:1;min-width:0}
.sec b{display:block;color:#EEF3FB;font-size:13px;font-weight:600}
.sec .count{flex:none;min-width:20px;height:18px;padding:0 5px;border-radius:9px;background:rgba(255,255,255,.12);color:#EEF3FB;font-size:11px;font-weight:600;display:grid;place-items:center}
.sec .chev{flex:none;width:14px;height:14px;color:#EEF3FB;transition:transform .2s}
.sec[aria-expanded="true"] .chev{transform:rotate(90deg)}
:root[data-theme="dark"] .sec{background:var(--accent-grad);color:rgba(255,255,255,.75)}
:root[data-theme="dark"] .sec b{color:#fff}
.search{grid-column:3;width:clamp(200px,22vw,300px);display:flex;align-items:center;gap:6px;padding:0 10px;height:36px;border:1px solid var(--line);border-radius:18px;background:var(--panel);color:var(--muted)}
.search kbd{font:11px var(--mono);color:var(--muted);border:1px solid var(--line);border-radius:4px;padding:0 5px;line-height:16px}
.search:focus-within kbd{display:none}
.search:focus-within{border-color:var(--commit)}
.search svg{width:15px;height:15px;flex:none}
.search input{flex:1;min-width:0;border:0;background:transparent;color:var(--ink);font:13px var(--sans);outline:none}
.nomatch{margin:12px;color:var(--muted);font-size:13px;text-align:center}
.cat[hidden]{display:none}
.speed{display:inline-flex;border:1px solid var(--line);border-radius:15px;overflow:hidden;margin-right:4px}
.speed button{border:0;background:transparent;font-size:11.5px;font-weight:600;color:var(--muted);padding:5px 7px;cursor:pointer}
.speed button+button{border-left:1px solid var(--line)}
.speed button[aria-pressed="true"]{background:var(--chip);color:var(--ink)}
.tabs{display:flex;gap:4px}
.tabs button{border:0;background:transparent;font:600 13.5px var(--sans);color:var(--muted);padding:4px 8px;border-radius:7px;cursor:pointer}
.tabs button[aria-selected="true"]{color:var(--ink);background:var(--chip)}
.tabs button[hidden]{display:none}
.quiz{padding:10px 14px 14px}
.quiz .qtop{display:flex;justify-content:space-between;font-size:12px;color:var(--muted);margin-bottom:6px}
.quiz .qq{font-weight:600;font-size:14px;margin:0 0 8px}
.quiz pre{margin:0 0 10px;padding:8px 12px;border-radius:8px;background:var(--term-bg);color:#C9D3E3;font:12.5px/1.6 var(--mono);overflow-x:auto}
:root[data-theme="dark"] .quiz pre{background:#fff;color:#172033}
.quiz .opts{display:flex;flex-direction:column;gap:6px}
.quiz .opt{text-align:left;padding:7px 12px;border:1px solid var(--line);border-radius:8px;background:var(--panel);font:13px var(--mono);cursor:pointer;transition:background .2s,border-color .2s}
.quiz .opt:hover:not(:disabled){border-color:var(--commit)}
.quiz .opt:disabled{cursor:default}
.quiz .opt.right{background:var(--green-soft);border-color:var(--green);color:var(--green);font-weight:600}
.quiz .opt.wrong{background:var(--red-soft);border-color:var(--red);color:var(--red)}
.quiz .fb{margin:10px 0 0;font-size:13px;line-height:1.5}
.quiz .fb b.ok{color:var(--green)}.quiz .fb b.no{color:var(--red)}
.quiz .fb code,.quiz .qq code{font:12px var(--mono);background:var(--chip);padding:0 4px;border-radius:4px}
.quiz .qnext{margin-top:10px;height:30px;padding:0 14px;border-radius:15px;border:1px solid var(--commit);background:var(--commit);color:var(--panel);font-weight:600;font-size:13px;cursor:pointer}
:root[data-theme="dark"] .quiz .qnext{background:var(--accent-grad);border-color:transparent;color:#fff}
.quiz .score{font-size:15px;font-weight:600;margin:4px 0}
.qlist{list-style:none;margin:4px 0 0;padding:0;display:flex;flex-direction:column;gap:2px}
.qlist[hidden]{display:none}
.qlist button{width:100%;text-align:left;padding:6px 10px;border-radius:9px;border:1px solid transparent;background:transparent;cursor:pointer;transition:background .2s,border-color .2s}
.qlist button:hover{background:var(--chip)}
.qlist .cmd{display:block;font-weight:600;font-size:13px;line-height:1.35}
.qlist .desc{display:block;font-size:12px;color:var(--muted);margin-top:1px}
.qlist li.active button{background:var(--chip);border-color:var(--commit)}
/* Code panel */
.query .panel-body{background:var(--term-bg)}
.code{margin:0;padding:10px 0;font:13.5px/1.75 var(--mono);color:#C9D3E3;min-width:max-content}
.code .row{display:grid;grid-template-columns:44px 1fr;padding-right:16px;border-left:3px solid transparent;transition:background .3s,border-color .3s}
.code .gut{color:#56627A;text-align:right;padding-right:14px;user-select:none}
.code .txt{white-space:pre}
.code .row.blk{background:rgba(127,162,255,.10);border-left-color:rgba(127,162,255,.55)}
.code .row.skip .txt{opacity:.32}
:root[data-theme="dark"] .code .row.blk{background:rgba(79,70,229,.07);border-left-color:rgba(79,70,229,.4)}
.code .row.cur{background:rgba(217,119,87,.22);border-left-color:var(--title)}
.code .row.cur .gut{color:#F4B69E}
.code .k{color:#7FA2FF;font-weight:600}
.code .s{color:#F2C27B}
.code .n{color:#63E6BE}
.code .f{color:#E599F7}
.code .c{color:#77849A;font-style:italic}
.code .ph{display:block;padding:2px 16px;color:#77849A;font-family:var(--sans)}
:root[data-theme="dark"] .query .panel-body{background:#FFFFFF}
:root[data-theme="dark"] .code{color:#172033}
:root[data-theme="dark"] .code .gut{color:#9AA3C4}
:root[data-theme="dark"] .code .k{color:#4F46E5}
:root[data-theme="dark"] .code .s{color:#B25E09}
:root[data-theme="dark"] .code .n{color:#15803D}
:root[data-theme="dark"] .code .f{color:#A21CAF}
:root[data-theme="dark"] .code .c,:root[data-theme="dark"] .code .ph{color:#6B78B8}
:root[data-theme="dark"] .code .row.cur{background:rgba(217,119,87,.16)}
:root[data-theme="dark"] .code .row.cur .gut{color:#C2552F}
.run{margin-left:auto;height:30px;padding:0 14px;border-radius:15px;border:1px solid var(--commit);background:var(--commit);color:var(--panel);font-weight:600;font-size:13px;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
.run:disabled{opacity:.45;cursor:default}
.run svg{width:13px;height:13px}
:root[data-theme="dark"] .run{background:var(--accent-grad);border-color:transparent;color:#fff}
/* Output: player, chips, caption, console */
.empty{height:100%;display:grid;place-items:center;text-align:center;padding:16px;color:var(--muted);font-size:13.5px;line-height:1.5}
.player{margin-left:auto;display:flex;align-items:center;gap:5px}
.pbtn{width:30px;height:30px;border-radius:50%;border:1px solid var(--line);background:var(--panel);color:var(--ink);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;padding:0}
.pbtn svg{display:block;flex:none;width:13px;height:13px}
.pbtn.primary{background:var(--commit);border-color:var(--commit);color:var(--panel)}
:root[data-theme="dark"] .pbtn.primary{background:var(--accent-grad);border-color:transparent;color:#fff}
.pbtn:disabled{opacity:.4;cursor:default}
.step-count{min-width:34px;text-align:right;font-size:12.5px;font-weight:400;color:var(--muted);font-variant-numeric:tabular-nums}
.output .panel-body{display:flex;flex-direction:column;overflow:hidden}
.chips{flex:none;display:flex;align-items:center;gap:3px;overflow-x:auto;scrollbar-width:none;padding:8px 10px 0}
.chips::-webkit-scrollbar{display:none}
.chip{flex:none;height:26px;padding:0 10px 0 4px;border-radius:13px;border:1px solid var(--line);background:transparent;font:600 11.5px var(--mono);color:var(--muted);cursor:pointer;display:inline-flex;align-items:center;gap:6px;transition:background .25s,color .25s,border-color .25s}
.chip-n{width:18px;height:18px;border-radius:50%;background:var(--chip);display:grid;place-items:center;font-size:10px}
.chip.done{color:var(--ink)}
.chip.done .chip-n{background:var(--green-soft);color:var(--green)}
.chip.active{background:var(--title);border-color:var(--title);color:#fff}
.chip.active .chip-n{background:rgba(255,255,255,.25);color:#fff}
.arrow{flex:none;color:var(--muted);font-size:13px}
.caption{flex:none;margin:0;padding:8px 12px;font-size:13.5px;line-height:1.5;min-height:3.6em}
.caption code{font:12.5px var(--mono);background:var(--chip);padding:1px 5px;border-radius:4px}
.caption .tag{display:inline-block;margin-right:6px;padding:1px 8px;border-radius:9px;background:var(--green-soft);color:var(--green);font-size:12px;font-weight:600}
.output .panel-body > .empty{margin:10px;height:calc(100% - 20px);border-radius:9px;background:var(--term-bg);color:#8793A8}
:root[data-theme="dark"] .output .panel-body > .empty{background:#FFFFFF;color:#6B78B8}
.nsel{margin-left:auto;display:inline-flex;align-items:center;gap:2px;font:600 12px var(--mono);color:var(--muted)}
.nsel[hidden]{display:none}
.nsel span{margin-right:4px}
.nsel button{width:24px;height:24px;border:1px solid var(--line);border-radius:6px;background:var(--panel);font:600 12px var(--mono);color:var(--muted);cursor:pointer;padding:0}
.nsel button[aria-pressed="true"]{background:var(--title);border-color:var(--title);color:#fff}
.nsel:not([hidden]) + .run{margin-left:10px}
.console .prow{display:flex;height:22px;align-items:center;padding-left:4px;border-radius:4px;transition:background .3s}
.console .prow.cur{background:rgba(217,119,87,.16)}
.console .prow.new{animation:lineIn .5s ease both}
.console .pc{width:15px;text-align:center;font:600 16px var(--mono);color:#EEF3FB}
.console .pc.sp{color:#56627A;font-weight:400}
.console .pc.hit{color:var(--title);transform:scale(1.25)}
.console .pkey{font-weight:400;margin-left:6px}
:root[data-theme="dark"] .console .pc{color:#172033}
:root[data-theme="dark"] .console .pc.sp{color:#B8BFD9}
.console{flex:1;min-height:0;margin:0 10px 10px;border-radius:9px;background:var(--term-bg);color:#C9D3E3;overflow:auto;font:13px/1.6 var(--mono);padding:8px 12px;scrollbar-width:thin}
.console .clbl{display:block;font:600 11.5px var(--sans);color:#8793A8;margin-bottom:4px}
.console .cline{display:block;white-space:pre-wrap}
.console .cline::before{content:'› ';color:#56627A}
.console .cline.new{animation:lineIn .5s ease both}
.console .none{color:#77849A;font-family:var(--sans);font-size:12.5px}
.console .typed{color:#63E6BE;font-weight:600}
.console .err{color:#FF8A80;font-weight:600}
:root[data-theme="dark"] .console .err{color:#C9372F}
:root[data-theme="dark"] .console{background:#FFFFFF;color:#172033}
:root[data-theme="dark"] .console .clbl,:root[data-theme="dark"] .console .none{color:#6B78B8}
:root[data-theme="dark"] .console .cline::before{color:#9AA3C4}
:root[data-theme="dark"] .console .typed{color:#15803D}
@keyframes lineIn{from{opacity:0;transform:translateX(-6px)}}
/* Memory: frames on the left, objects on the right, arrows between */
.memory .panel-body{position:relative}
.mem{position:relative;display:grid;grid-template-columns:minmax(150px,180px) minmax(170px,1fr);column-gap:44px;padding:12px 14px 16px;min-height:100%;align-items:start;align-content:start}
.colh{font-size:12px;font-weight:600;color:var(--muted);margin:0 0 8px}
.stack,.heap{display:flex;flex-direction:column;gap:10px;position:relative;z-index:1}
.heap2{display:flex;flex-wrap:wrap;gap:12px 28px;align-items:flex-start}
.hc{display:flex;flex-direction:column;gap:8px;min-width:0;max-width:100%}
.hc .obj{padding:5px 8px 7px}
.hc .cell{min-width:30px}
.hc .cell span{padding:3px 6px}
.orow{display:flex;flex-wrap:wrap;gap:12px 16px;align-items:flex-start}
.orow .obj{padding:5px 8px 8px}
.orow .cell{min-width:32px}
.frame{border:1px solid var(--line);border-radius:10px;background:var(--panel);overflow:hidden;transition:opacity .3s,border-color .3s}
.frame .fh{display:flex;align-items:center;gap:6px;padding:5px 10px;background:var(--chip);font:600 12.5px var(--mono)}
.frame .fh{white-space:nowrap}
.frame .fh .st{margin-left:auto;font:500 11px var(--sans);color:var(--muted)}
.frame.active{border-color:var(--commit);box-shadow:0 0 0 1px var(--commit)}
.frame.active .fh .st{color:var(--commit);font-weight:600}
.frame.paused{opacity:.62}
.frame.enter{animation:pop .4s ease both}
.var{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:center;gap:10px;padding:5px 10px;border-top:1px solid var(--line);font:13px var(--mono);min-height:32px}
.var:first-of-type{border-top:0}
.var .vn{white-space:nowrap}
.var.long{grid-template-columns:1fr;row-gap:3px}
.var.long .vn{white-space:normal;overflow-wrap:anywhere}
.var.long .vv.prim{justify-self:start;text-align:left}
.mem > div{min-width:0}
.heap,.heap2{padding-right:30px}
.var .vv.prim{overflow-wrap:anywhere;text-align:right;white-space:pre-wrap}
.var .vv{justify-self:end;font-weight:600}
.var .vv.prim{padding:1px 8px;border-radius:6px;background:var(--chip)}
.cref .dot{display:block;width:9px;height:9px;border-radius:50%;background:var(--muted)}
.var .dot{display:block;width:10px;height:10px;border-radius:50%;background:var(--commit)}
.var.fresh{animation:flash 1.6s ease both}
.var.fresh .dot{background:var(--title)}
.var.ret{background:var(--green-soft)}
.var.ret .vn{font-family:var(--sans);font-size:12.5px;color:var(--green);font-weight:600}
.var.ret .vv.prim{background:transparent;color:var(--green)}
.frame .novars{padding:6px 10px;font-size:12.5px;color:var(--muted)}
@keyframes flash{0%,45%{background:var(--amber-soft)}100%{background:transparent}}
@keyframes pop{from{opacity:0;transform:scale(.94)}}
.obj{border:1px solid var(--line);border-radius:10px;background:var(--panel);padding:6px 10px 9px;width:max-content;max-width:100%}
.obj.enter{animation:pop .45s ease both}
.obj .oh{display:flex;align-items:baseline;gap:8px;font-size:12px;color:var(--muted);margin-bottom:5px;font-weight:500}
.obj .oh b{font:600 12.5px var(--mono);color:var(--ink)}
.cells{display:flex;flex-wrap:wrap}
.cell{min-width:40px;border:1px solid var(--line);margin-left:-1px;text-align:center;transition:background .4s,border-color .4s}
.cell:first-child{margin-left:0;border-radius:6px 0 0 6px}
.cell:last-child{border-radius:0 6px 6px 0}
.cell:only-child{border-radius:6px}
.cell small{display:block;font:10.5px var(--mono);color:var(--muted);border-bottom:1px solid var(--line);padding:1px 0}
.cell span{display:block;font:600 13.5px var(--mono);padding:4px 8px}
.cell.new{background:var(--green-soft);border-color:var(--green);position:relative;z-index:1;animation:pop .45s ease both}
.cell.new span{color:var(--green)}
.cell.cur{background:var(--amber-soft);border-color:var(--amber);position:relative;z-index:1}
.cell.cur span{color:var(--amber)}
.cell.sel{background:color-mix(in srgb,var(--commit) 14%,transparent);border-color:var(--commit);position:relative;z-index:1}
.cell.sel span{color:var(--commit)}
.cell.chg{background:var(--amber-soft);border-color:var(--amber);position:relative;z-index:1}
.cell.chg span{color:var(--amber)}
.cell.del{background:var(--red-soft);border-color:var(--red);position:relative;z-index:1}
.cell.del span{color:var(--red);text-decoration:line-through}
.cell small.ng{border-bottom:0;border-top:1px solid var(--line)}
.obj.seq .cell{min-width:24px}
.obj.seq .cell span{padding:3px 5px}
.obj.seq .cells{row-gap:4px}
.cell .sp{font-style:normal;color:var(--muted);font-weight:400}
.obj.set .cell{border-radius:14px!important;margin:0 4px 4px 0}
.obj.set .cells{margin-bottom:-4px}
.cref{display:grid;place-items:center;min-height:19px}
.dict{display:grid;border:1px solid var(--line);border-radius:6px;overflow:hidden;font:13px var(--mono)}
.drow{display:grid;grid-template-columns:auto auto;gap:14px;justify-content:space-between;padding:4px 10px;border-top:1px solid var(--line);align-items:center;transition:background .4s}
.drow:first-child{border-top:0}
.drow .dk{color:var(--muted)}
.drow .dv{font-weight:600}
.drow.new{background:var(--green-soft)}.drow.new .dv,.drow.new .dk{color:var(--green)}
.drow.chg{background:var(--amber-soft)}.drow.chg .dv{color:var(--amber)}
.drow.sel{background:color-mix(in srgb,var(--commit) 14%,transparent)}.drow.sel .dv{color:var(--commit)}
.drow.del{background:var(--red-soft)}.drow.del span{color:var(--red);text-decoration:line-through}
.wires path.inner{stroke:var(--muted);stroke-width:1.5;stroke-dasharray:4 3}
.obj .sig{font:600 13.5px var(--mono);padding:2px 0}
.obj .sig .k{color:var(--commit)}
.evalbar{grid-column:1/-1;display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin:0 0 12px;padding:8px 10px;border-radius:10px;background:var(--chip);border:1px dashed var(--line);animation:pop .35s ease both}
.evalbar .el{font-size:12px;font-weight:600;color:var(--muted);margin-right:4px}
.evalbar .stg{font:600 13px var(--mono);padding:2px 8px;border-radius:6px;background:var(--panel);border:1px solid var(--line);white-space:pre}
.evalbar .stg.res{background:var(--title);border-color:var(--title);color:#fff}
.evalbar .ar{color:var(--muted);font-size:13px}
.raisebar{grid-column:1/-1;display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:0 0 12px;padding:8px 10px;border-radius:10px;background:var(--red-soft);border:1px solid var(--red);animation:pop .35s ease both}
.raisebar .el{font-size:12px;font-weight:700;color:var(--red)}
.raisebar .rx{font:600 13px var(--mono);color:var(--red);overflow-wrap:anywhere}
.raisebar.caught{background:var(--green-soft);border-color:var(--green)}
.raisebar.caught .el,.raisebar.caught .rx{color:var(--green)}
.obj.exc{border-color:var(--red);background:var(--red-soft)}
.obj.exc .oh b,.obj.exc .pv{color:var(--red)}
.obj.cls{border-color:color-mix(in srgb,var(--commit) 45%,var(--line))}
.obj.cls .oh b .k,.drow.meth .k{color:var(--commit)}
.drow.meth{grid-template-columns:1fr}
.drow.meth .dv{font-weight:500}
.drow .dec{color:var(--amber);font-weight:600}
.drow.par .dk{font-family:var(--sans);font-size:11.5px}
.obj.inst .oh{align-items:center}
.obj.inst .clink{margin-left:auto;padding-left:10px}
.obj.inst .dict{min-width:120px}
.obj.inst .dict .novars{display:block;padding:3px 8px;font-size:12px;color:var(--muted)}
.mem.shell{grid-template-columns:1fr}
.mem.shell .heap{flex-direction:row;flex-wrap:wrap;align-items:flex-start}
.drow .dk.pk{color:var(--ink);font-weight:500}
.tree{border:1px solid var(--line);border-radius:6px;overflow:hidden;font:12.5px var(--mono)}
.tree .tr{padding:3px 10px;border-top:1px solid var(--line);white-space:nowrap;transition:background .4s}
.tree .tr:first-child{border-top:0}
.tree .tr.dir{font-weight:600;color:var(--commit)}
.tree .br{color:var(--muted);margin-right:5px;font-weight:400}
.tree .tr.new{background:var(--green-soft);color:var(--green)}
.tree .tr.sel{background:color-mix(in srgb,var(--commit) 14%,transparent)}
.ndg{display:flex;flex-direction:column;gap:0}
.ndg.two .cells .cell{margin-top:-1px;border-radius:0!important}
.ndg.two{padding-top:1px}
.dfw{overflow-x:auto;max-width:100%}
.dft{border-collapse:collapse;font:12.5px var(--mono)}
.dft th,.dft td{border:1px solid var(--line);padding:3px 9px;text-align:right;white-space:nowrap;transition:background .4s}
.dft thead th{font-weight:600;background:var(--chip)}
.dft .dty th{font-weight:400;font-size:10.5px;color:var(--muted);background:var(--panel)}
.dft th.ix{color:var(--muted);font-weight:400;background:var(--panel);text-align:left}
.dft td{font-weight:500}
.dft .nan{color:var(--red);font-style:italic;font-weight:400}
.dft th.sel,.dft td.sel{background:color-mix(in srgb,var(--commit) 12%,transparent)}
.dft th.chg,.dft td.chg{background:var(--amber-soft)}
.dft th.new,.dft td.new,.dft td.cnew{background:var(--green-soft);color:var(--green)}
.dft tr.sel td{background:color-mix(in srgb,var(--commit) 12%,transparent)}
.dft tr.chg td{background:var(--amber-soft)}
.dft tr.cur td{background:var(--amber-soft)}
.dft tr.new td{background:var(--green-soft)}
.dft tr.del td,.dft tr.del th.ix{opacity:.4;text-decoration:line-through}
.figsvg{display:block;max-width:100%;height:auto}
.figsvg .ax{stroke:var(--muted);stroke-width:1}
.figsvg .tk{font:9.5px var(--mono);fill:var(--muted)}
.figsvg .ttl{font:600 11px var(--sans);fill:var(--ink)}
.figsvg .lbl{font:10px var(--sans);fill:var(--muted)}
.figsvg .ln{fill:none;stroke:var(--commit);stroke-width:2}
.figsvg .pt{fill:var(--commit)}
.figsvg .fitln{stroke:var(--title);stroke-dasharray:5 4;stroke-width:1.8}
.figsvg .ptp{fill:var(--title);stroke:var(--panel);stroke-width:2}
.fitpill{margin-left:auto;padding:1px 8px;border-radius:9px;font-size:11px;font-weight:600;background:var(--chip);color:var(--muted)}
.fitpill.on{background:var(--green-soft);color:var(--green)}
.obj.est .oh{align-items:center;gap:10px}
.obj.est .dv{font-size:12.5px;white-space:normal;text-align:right;overflow-wrap:anywhere}
.obj.est .drow{grid-template-columns:auto minmax(0,1fr)}
.obj.est .dk{white-space:nowrap}
.psteps{display:flex;flex-direction:column;align-items:stretch}
.pst{display:grid;grid-template-columns:20px 1fr auto;gap:8px;align-items:center;padding:5px 8px;border:1px solid var(--line);border-radius:7px;font:12.5px var(--mono);transition:background .4s}
.pst .pn{width:18px;height:18px;border-radius:50%;background:var(--chip);display:grid;place-items:center;font-size:10.5px;color:var(--muted)}
.pst .ps{font:600 11px var(--sans);color:var(--muted)}
.pst.sel{background:color-mix(in srgb,var(--commit) 12%,transparent);border-color:var(--commit)}
.pst.new{background:var(--green-soft);border-color:var(--green)}.pst.new .ps{color:var(--green)}
.parr{text-align:center;color:var(--muted);font-size:12px;line-height:1.3}
.figsvg .bar{fill:var(--commit);opacity:.8}
.figsvg .er{stroke:var(--ink);stroke-width:1.5}
.fdefs{margin-top:6px;font-size:12px}
.obj.file{min-width:170px}
.obj.file .oh{flex-wrap:wrap}
.obj.file .oh b{margin-right:2px}
.obj.file .oh .mode{font:11.5px var(--mono);padding:0 5px;border-radius:4px;background:var(--chip)}
.obj.file .oh .fst{margin-left:auto;padding-left:8px;font-size:11px;font-weight:600;color:var(--green)}
.obj.file.closed .oh .fst{color:var(--muted)}
.obj.file.closed .flines{opacity:.55}
.flines{border:1px solid var(--line);border-radius:6px;overflow:hidden;font:12.5px var(--mono);background:var(--chip)}
.fl{display:grid;grid-template-columns:22px 1fr;border-top:1px solid var(--line);transition:background .4s}
.fl:first-child{border-top:0}
.fl .fn{color:var(--muted);text-align:right;padding:3px 6px 3px 0;font-size:10.5px;border-right:1px solid var(--line)}
.fl .ft{padding:3px 8px;white-space:pre-wrap;overflow-wrap:anywhere;background:var(--panel)}
.fl.new .ft{background:var(--green-soft);color:var(--green)}
.fl.sel .ft{background:color-mix(in srgb,var(--commit) 14%,var(--panel));color:var(--commit)}
.fl.cur .ft{background:var(--amber-soft);color:var(--amber)}
.frame .fh{overflow:hidden;text-overflow:ellipsis}
.mem.solo{grid-template-columns:minmax(150px,340px)}
.obj.prim{display:flex;flex-wrap:wrap;align-items:baseline;gap:2px 10px;padding:5px 12px}
.obj.prim .oh{margin:0}
.obj.prim .pv{font:600 13.5px var(--mono)}
.obj.gone{opacity:.45;border-style:dashed}
.obj.gone::after{content:'no names left';font-size:11px;color:var(--muted)}
.wires path.hot{stroke:var(--title);stroke-width:2.2}
.wires{position:absolute;left:0;top:0;pointer-events:none;overflow:visible;z-index:2}
.wires path{fill:none;stroke:var(--commit);stroke-width:1.8}
.wires path.fresh{stroke:var(--title);stroke-width:2.2;stroke-dasharray:1;stroke-dashoffset:1;animation:draw .7s ease forwards}
@keyframes draw{to{stroke-dashoffset:0}}
/* Variables panel */
.flist{list-style:none;margin:0;padding:4px 0}
.flist .fgrp{padding:8px 12px 4px;font-size:12px;font-weight:600;color:var(--muted);border-bottom:1px solid var(--line)}
.flist li.v{padding:7px 12px;border-bottom:1px solid var(--line)}
.flist .fn{display:block;font:600 12.5px var(--mono);overflow-wrap:anywhere}
.flist .ft{display:block;font:12px var(--mono);color:var(--muted);margin-top:2px}
.flist .pk{display:inline-block;margin-left:4px;padding:0 5px;border-radius:4px;background:var(--amber-soft);color:var(--amber);font:600 10.5px var(--sans);vertical-align:1px}
.flist .emptyv{padding:10px 12px;color:var(--muted);font-size:12.5px;line-height:1.45}
/* Interview + call-outs */
.qa{margin:0;padding:4px 0}
.qa details{border-bottom:1px solid var(--line)}
.qa summary{padding:8px 12px;cursor:pointer;font-size:13px;font-weight:500;line-height:1.4;list-style:none;display:grid;grid-template-columns:14px 1fr;gap:6px}
.qa summary::-webkit-details-marker{display:none}
.qa summary::before{content:'+';color:var(--commit);font-weight:700}
.qa details[open] summary::before{content:'−'}
.qa p{margin:0;padding:0 12px 10px 32px;color:var(--muted);font-size:13px;line-height:1.5}
.qa code,.co code{font:12px var(--mono);background:var(--chip);padding:0 4px;border-radius:4px}
.co{list-style:none;margin:0;padding:8px;display:flex;flex-direction:column;gap:6px}
.co li{padding:7px 9px;border-left:3px solid var(--title);background:var(--chip);border-radius:0 6px 6px 0;font-size:12.5px;line-height:1.45}
.co li code{background:var(--panel)}
@media (max-width:900px){
header{grid-template-columns:auto 1fr auto;row-gap:8px}
.search{grid-column:1/-1;grid-row:2;width:100%}
.theme-btn{grid-column:3}
body{overflow:auto}
.app{height:auto;grid-template-rows:auto auto}
.main{grid-template-columns:1fr}
.side{max-height:220px}
.body{grid-template-columns:1fr;grid-template-rows:none}
.query,.output,.memory,.fields,.interview,.callouts{grid-area:auto;min-height:280px}
.memory{min-height:380px}
.mem{column-gap:44px}
}
@media (prefers-reduced-motion: reduce){*{transition:none!important;animation:none!important}.wires path.fresh{stroke-dasharray:none}}
</style>
</head>
<body>
<div class="app">
<header>
<span class="brand" role="img" aria-label="GK">GK</span>
<h1>Visualized Python Code</h1>
<div class="search">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
<input type="search" id="search" placeholder="Search concepts" aria-label="Search concepts" autocomplete="off">
<kbd aria-hidden="true">/</kbd>
</div>
<button class="theme-btn" id="themeBtn" aria-label="Switch to dark theme"></button>
</header>
<div class="main">
<aside class="panel side" aria-label="Concepts">
<div class="panel-head">Concepts</div>
<div class="panel-body"><nav id="qnav"></nav><p class="nomatch" id="nomatch" hidden>No concepts match your search.</p></div>
</aside>
<div class="body">
<section class="panel query" aria-label="Code">
<div class="panel-head">
Code
<div class="nsel" id="nsel" role="group" aria-label="Pattern size" hidden>
<span>n =</span><button>3</button><button>4</button><button>5</button><button>6</button><button>7</button>
</div>
<button class="run" id="runBtn" disabled>
<svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 4v16l13-8z"/></svg>Run
</button>
</div>
<div class="panel-body"><div class="code" id="code" aria-live="polite"></div></div>
</section>
<section class="panel output" aria-label="Output">
<div class="panel-head">
Output
<div class="player">
<div class="speed" role="group" aria-label="Autoplay speed">
<button data-ms="4500">Slow</button><button data-ms="2800">Normal</button><button data-ms="1400">Fast</button>
</div>
<span class="step-count" id="stepCount"></span>
<button class="pbtn" id="prevBtn" aria-label="Previous step" disabled><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="m15 6-6 6 6 6"/></svg></button>
<button class="pbtn primary" id="playBtn" aria-label="Play" disabled><svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 4v16l13-8z"/></svg></button>
<button class="pbtn" id="nextBtn" aria-label="Next step" disabled><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="m9 6 6 6-6 6"/></svg></button>
</div>
</div>
<div class="panel-body" id="output">
<div class="empty">Pick a concept, then press Run to watch it line by line.</div>
</div>
</section>
<section class="panel memory" aria-label="Memory">
<div class="panel-head">Memory<span class="hint">Names point to objects</span></div>
<div class="panel-body" id="memBody">
<div class="empty">Frames and objects appear here as the code runs.</div>
</div>
</section>
<section class="panel fields" aria-label="Variables">
<div class="panel-head">Variables</div>
<div class="panel-body"><ul class="flist" id="varList"><li class="emptyv">Each name and its type shows here.</li></ul></div>
</section>
<section class="panel interview" aria-label="Interview questions">
<div class="panel-head">
<div class="tabs" role="tablist">
<button role="tab" id="tabQA" aria-selected="true">Interview questions</button>
<button role="tab" id="tabQuiz" aria-selected="false" hidden>Test yourself</button>
</div>
<span class="hint" id="qaHint">Click a question to see the answer</span>
</div>
<div class="panel-body" id="interview"><div class="empty">Pick a concept to see related interview questions.</div></div>
</section>
<section class="panel callouts" aria-label="Call-outs">
<div class="panel-head">Call-outs</div>
<div class="panel-body" id="callouts"><div class="empty">Pick a concept to see what to watch out for.</div></div>
</section>
</div>
</div>
<footer>Built by Gopikrishna | <a href="mailto:gkrishna.ai.lab@gmail.com">gkrishna.ai.lab@gmail.com</a></footer>
</div>
<script>
const $ = id => document.getElementById(id);
const esc = t => String(t).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
/* ---------- Theme ---------- */
const SUN = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="4.2"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>';
const MOON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.5 14.2A8.5 8.5 0 0 1 9.8 3.5a8.5 8.5 0 1 0 10.7 10.7z"/></svg>';
function applyTheme(t){
document.documentElement.dataset.theme = t;
$('themeBtn').innerHTML = t === 'dark' ? SUN : MOON;
$('themeBtn').setAttribute('aria-label', t === 'dark' ? 'Switch to light theme' : 'Switch to dark theme');
}
let theme = 'light';
applyTheme(theme);
$('themeBtn').addEventListener('click', () => { theme = theme === 'dark' ? 'light' : 'dark'; applyTheme(theme); });
/* ---------- Trace builder ----------
Each step is a full snapshot of program state:
frames: [{name, vars:[[name, value]], ret}] value = number | string | null | {ref:id}
objs: {id: {t:'list', items:[...]} | {t:'function', sig}}
out: printed lines
Marks for the current step: fresh (var keys), newObjs, cells {id:{new:[i], cur:i}}, newFrame, newOut */
function trace(build, opts = {}){
const steps = [];
let s = {frames:[{name:'Global frame', vars:[]}], objs:{}, out:[]};
const step = (line, caption, fn) => {
const n = structuredClone({frames:s.frames, objs:s.objs, out:s.out});
n.fresh = []; n.newObjs = []; n.cells = {}; delete n.raised; delete n.caught;
if(fn) fn(n);
n.line = line; n.caption = caption; if(opts.shell) n.shell = true; if(opts.pattern) n.pat = true; else delete n.cur;
steps.push(n); s = n;
};
build(step);
steps[steps.length - 1].final = true;
return steps;
}
const topIdx = n => n.frames.length - 1;
function set(n, name, val, fi = topIdx(n)){
const f = n.frames[fi], v = f.vars.find(x => x[0] === name);
if(v) v[1] = val; else f.vars.push([name, val]);
n.fresh.push(fi + ':' + name);
}
function obj(n, id, o){ n.objs[id] = o; n.newObjs.push(id); }
function push(n, name, args){
const sig = args.map(([k, v]) => k + '=' + (isRef(v) ? '…' : show(v))).join(', ');
n.frames.push({name, title: args.length && sig.length <= 16 ? `${name}(${sig})` : name, vars:[]});
n.newFrame = topIdx(n);
args.forEach(([k, v]) => set(n, k, v));
}
function pop(n){ n.frames.pop(); }
function ret(n, v){ n.frames[topIdx(n)].ret = v; }
function out(n, line){ n.out.push(line); n.newOut = true; }
const F = v => ({py:'float', v}); // a float that prints with .0, e.g. F(180) -> 180.0
const expr = (n, ...stages) => { n.expr = stages; };
const CL = (n, cur) => ({L1:{cur}});
/* ---------- Concept library: [category, subtitle, [[title, description, code, steps, [[q, a]], [call-outs]]]] ---------- */
/* ---------- Pattern printing: generated from rules for any n ---------- */
const PAT = {n:4};
const RP = (c, k) => c.repeat(Math.max(0, k));
const L = k => String.fromCharCode(65 + k);
function patTrace(spec, n){
return trace(step => {
step(1, spec.intro ? spec.intro(n) : `<code>n = ${n}</code> sets the size. Change it with the n buttons above the code.`,
s => { set(s, 'n', n); obj(s, 'T1', {t:'DataFrame', hdr:'row formula', noIndex:true, cols:spec.cols, index:[], rows:[]}); });
if(spec.init) step(spec.init.line, spec.init.cap, s => spec.init.vars.forEach(([k, v]) => set(s, k, v)));
const rows = spec.rows(n);
rows.forEach((r, k) => {
step(r.line, spec.cap(r, k, n), s => {
Object.entries(r.vars).forEach(([a, b]) => set(s, a, b));
const T = s.objs.T1; T.index.push(k); T.rows.push(r.cols); s.cells.T1 = {rows:{new:[T.rows.length - 1]}};
s.out.push(r.text); s.newOut = true; s.cur = {r:k};
});
});
step(rows[rows.length - 1].line, spec.done(n), null);
}, {pattern:true});
}
function patItem(title, desc, spec, qa, notes){
const item = [title, desc, '', null, qa, notes, {pattern:true}];
item.refresh = () => { item[2] = spec.code(PAT.n); };
item[3] = () => spec.custom ? spec.custom(PAT.n) : patTrace(spec, PAT.n);
item.refresh();
return item;
}
const PY = (n, body) => `n = ${n}\n` + body;
/* Shared builder for "spaces then something" pyramids */
function pyramidRows(n, order, line, mk){
const st = {};
return order.map(i => { const r = mk(i, st); return {i, line, text:r.text, cols:r.cols, vars:Object.assign({i}, r.vars)}; });
}
const up = n => Array.from({length:n}, (_, k) => k + 1);
const down = n => up(n).reverse();
const PATTERN_SECTION = ['15. Pattern Printing', 'Stars, numbers and letters', [
patItem('Right-angle triangle', '*, **, *** · step by step', {
code: n => PY(n, `for i in range(1, n + 1):\n for j in range(i):\n print("*", end="")\n print()`),
custom: n => trace(step => {
step(1, `<code>n = ${n}</code> sets the size. Change it with the n buttons above the code. This first pattern goes one character at a time so you can see both loops working.`,
s => { set(s, 'n', n); obj(s, 'T1', {t:'DataFrame', hdr:'row formula', noIndex:true, cols:['row i', 'stars (= i)'], index:[], rows:[]}); });
for(let i = 1; i <= n; i++){
step(2, i === 1 ? 'The <b>outer loop</b> picks the row. <code>i = 1</code> is row 1.' : `Outer loop: next row, <code>i = ${i}</code>. The inner loop will run ${i} times.`, s => set(s, 'i', i));
for(let j = 0; j < i; j++){
step(4, i === 1 ? 'The <b>inner loop</b> prints the stars for this row. <code>end=""</code> stops Python moving to a new line after each star.'
: `<code>j = ${j}</code>: star ${j + 1} of ${i}, on the same line.`,
s => { set(s, 'j', j); if(j === 0) s.out.push('*'); else s.out[s.out.length - 1] += '*'; s.newOut = true; s.cur = {r:i - 1, c:j}; });
}
step(5, i === 1 ? 'A bare <code>print()</code> ends the row by printing a newline. The rule so far: row <code>i</code> has <code>i</code> stars.' : `Row ${i} done: ${i} stars, then a newline.`,
s => { const T = s.objs.T1; T.index.push(i - 1); T.rows.push([i, i]); s.cells.T1 = {rows:{new:[i - 1]}}; s.cur = {r:i - 1}; });
}
step(5, `Finished: ${n} rows. The outer loop controls <b>how many rows</b>; the inner loop controls <b>what goes in each row</b>. Every pattern in this section follows that idea.`, null);
}, {pattern:true}),
}, [['How do nested loops create a pattern?', 'The outer loop runs once per row; the inner loop runs once per character in that row. The inner loop’s range depends on <code>i</code>.'],
['Why <code>end=""</code>?', '<code>print</code> normally adds a newline. <code>end=""</code> keeps the next character on the same line.'],
['How many stars are printed in total?', '1 + 2 + … + n = n(n + 1) / 2. For n = 4 that’s 10.']],
['Shortcut: <code>print("*" * i)</code> prints a whole row at once.',
'Forgetting the bare <code>print()</code> puts every star on one line.',
'Interviewers usually want the nested-loop version, then ask for the one-liner.']),
patItem('Inverted right triangle', '****, ***, **, *', {
code: n => PY(n, `for i in range(n, 0, -1):\n for j in range(i):\n print("*", end="")\n print()`),
cols: ['row i', 'stars (= i)'],
rows: n => pyramidRows(n, down(n), 5, i => ({text:RP('*', i), cols:[i, i], vars:{j:i - 1}})),
cap: (r, k, n) => k === 0 ? `<code>range(n, 0, -1)</code> counts down, so the first row has <code>i = ${n}</code> and prints ${n} stars.` : `<code>i = ${r.i}</code>: ${r.i} star${r.i > 1 ? 's' : ''}. One fewer each row.`,
done: n => 'Same inner loop as the right-angle triangle; only the outer loop’s direction changed.',
}, [['What does <code>range(n, 0, -1)</code> produce?', `n, n − 1, …, 1. The stop value 0 is excluded and the step −1 counts down.`],
['Another way without a negative step?', 'Loop <code>i</code> from 1 to n and print <code>n − i + 1</code> stars.'],
['How would you right-align it?', 'Print <code>n − i</code> spaces before the stars in each row.']],
['Shortcut: <code>for i in range(n, 0, -1): print("*" * i)</code>.',
'Reversing a pattern usually means reversing the outer loop only.',
'Off-by-one errors are the usual bug: check the first and last row.']),
patItem('Left-leaning triangle', ' *, **, *** (right-aligned)', {
code: n => PY(n, `for i in range(1, n + 1):\n for s in range(n - i):\n print(" ", end="")\n for j in range(i):\n print("*", end="")\n print()`),
cols: ['row i', 'spaces (n − i)', 'stars (i)'],
rows: n => pyramidRows(n, up(n), 7, (i, st) => { if(n - i > 0) st.s = n - i - 1; return {text:RP(' ', n - i) + RP('*', i), cols:[i, n - i, i], vars:Object.assign({}, 's' in st ? {s:st.s} : {}, {j:i - 1})}; }),
cap: (r, k, n) => k === 0 ? `Each row now has two inner loops: <b>spaces first</b>, then stars. Row 1 gets ${n - 1} spaces (shown as dots) and 1 star.` : r.i === n ? `Last row: <code>n − i = 0</code>, so no spaces at all.` : `<code>i = ${r.i}</code>: ${n - r.i} space${n - r.i > 1 ? 's' : ''}, ${r.i} stars.`,
done: n => 'Spaces + stars always add up to n here, which is what lines the right edge up.',
}, [['Why do the stars line up on the right?', 'Spaces + stars = (n − i) + i = n for every row, so every row ends at the same column.'],
['What if you used <code>n − i + 1</code> spaces?', 'Every row shifts one column right; the shape stays the same but has an extra blank column.'],
['Shortcut?', '<code>print(" " * (n - i) + "*" * i)</code>, or <code>print(("*" * i).rjust(n))</code>.']],
['Spaces are invisible in a terminal, which is why they’re shown as dots here.',
'This shape is called a right-aligned or mirrored right triangle in many textbooks.',
'Trailing spaces would be invisible; leading spaces are what create the shape.']),
patItem('Pyramid', 'centred triangle', {
code: n => PY(n, `for i in range(1, n + 1):\n for s in range(n - i):\n print(" ", end="")\n for j in range(2 * i - 1):\n print("*", end="")\n print()`),
cols: ['row i', 'spaces (n − i)', 'stars (2i − 1)'],
rows: n => pyramidRows(n, up(n), 7, (i, st) => { if(n - i > 0) st.s = n - i - 1; return {text:RP(' ', n - i) + RP('*', 2 * i - 1), cols:[i, n - i, 2 * i - 1], vars:Object.assign({}, 's' in st ? {s:st.s} : {}, {j:2 * i - 2})}; }),
cap: (r, k, n) => k === 0 ? `Like the left-leaning triangle, but stars grow by <b>2</b> per row (1, 3, 5…): <code>2i − 1</code>. That keeps the peak centred.` : `<code>i = ${r.i}</code>: ${n - r.i} space${n - r.i === 1 ? '' : 's'}, <code>2 × ${r.i} − 1 = ${2 * r.i - 1}</code> stars.`,
done: n => `The base is <code>2n − 1 = ${2 * n - 1}</code> stars wide. Look at the formula table: that’s the whole pattern in two columns.`,
}, [['Why <code>2i − 1</code> stars?', 'Odd numbers (1, 3, 5, …) let the row grow by one star on each side while staying symmetric.'],
['How wide is the base?', '<code>2n − 1</code> characters.'],
['Shortcut?', '<code>print(" " * (n - i) + "*" * (2 * i - 1))</code>, or <code>("*" * (2*i - 1)).center(2*n - 1)</code>.']],
['Find the formula first: write a small table of row → spaces → stars, as shown in Memory.',
'A star followed by a space (<code>"* "</code>) with i stars also makes a pyramid, a popular variant.',
'The pyramid is the building block for the diamond and hourglass.']),
patItem('Inverted pyramid', 'centred, pointing down', {
code: n => PY(n, `for i in range(n, 0, -1):\n for s in range(n - i):\n print(" ", end="")\n for j in range(2 * i - 1):\n print("*", end="")\n print()`),
cols: ['row i', 'spaces (n − i)', 'stars (2i − 1)'],
rows: n => pyramidRows(n, down(n), 7, (i, st) => { if(n - i > 0) st.s = n - i - 1; return {text:RP(' ', n - i) + RP('*', 2 * i - 1), cols:[i, n - i, 2 * i - 1], vars:Object.assign({}, 's' in st ? {s:st.s} : {}, {j:2 * i - 2})}; }),
cap: (r, k, n) => k === 0 ? `Same body as the pyramid, but <code>i</code> counts down from ${n}. The widest row comes first, with no spaces.` : `<code>i = ${r.i}</code>: ${n - r.i} space${n - r.i === 1 ? '' : 's'}, ${2 * r.i - 1} star${r.i > 1 ? 's' : ''}.`,
done: n => 'Only the outer loop changed. The formulas stayed exactly the same.',
}, [['What changed compared with the pyramid?', 'Only <code>range(1, n + 1)</code> became <code>range(n, 0, -1)</code>.'],
['Could you keep <code>i</code> counting up?', 'Yes: use <code>i − 1</code> spaces and <code>2(n − i) + 1</code> stars.'],
['Shortcut?', '<code>for i in range(n, 0, -1): print(" " * (n - i) + "*" * (2*i - 1))</code>.']],
['Write the formula table for the first and last row; that catches most off-by-one mistakes.',
'Pyramid + inverted pyramid = diamond (next concept).',
'Inverted pyramid on top of a pyramid makes an hourglass.']),
patItem('Diamond', 'pyramid + inverted pyramid', {
code: n => PY(n, `for i in range(1, n + 1):\n for s in range(n - i):\n print(" ", end="")\n for j in range(2 * i - 1):\n print("*", end="")\n print()\nfor i in range(n - 1, 0, -1):\n for s in range(n - i):\n print(" ", end="")\n for j in range(2 * i - 1):\n print("*", end="")\n print()`),
cols: ['row i', 'spaces (n − i)', 'stars (2i − 1)'],
rows: n => { const st = {}; const mk = (i, line) => { if(n - i > 0) st.s = n - i - 1; return {i, line, text:RP(' ', n - i) + RP('*', 2 * i - 1), cols:[i, n - i, 2 * i - 1], vars:Object.assign({i}, 's' in st ? {s:st.s} : {}, {j:2 * i - 2})}; };
return [...up(n).map(i => mk(i, 7)), ...down(n - 1).map(i => mk(i, 13))]; },
cap: (r, k, n) => k === 0 ? 'The <b>top half</b> is an ordinary pyramid.' : k === n - 1 ? `Middle row, <code>i = ${n}</code>: the widest, ${2 * n - 1} stars.` : k === n ? `The <b>bottom half</b> is a second loop counting down from <code>n − 1 = ${n - 1}</code>, so the middle row isn’t printed twice.` : `<code>i = ${r.i}</code>: ${n - r.i} space${n - r.i === 1 ? '' : 's'}, ${2 * r.i - 1} star${r.i > 1 ? 's' : ''}.`,
done: n => `${2 * n - 1} rows in total. Same formulas in both halves; only the direction of <code>i</code> changes.`,
}, [['Why does the second loop start at <code>n − 1</code>?', 'Starting at n would repeat the widest middle row.'],
['How many rows does a diamond have?', '<code>2n − 1</code>.'],
['Can you do it with one loop?', 'Yes: loop <code>k</code> from 1 to 2n − 1 and use <code>i = n − abs(n − k)</code> as the row size.']],
['Avoid copy-paste in real code: put the row body in a function <code>row(i)</code> and call it from both loops.',
'The hourglass is the same two loops in the opposite order.',
'A hollow diamond combines this with the hollow-pyramid condition.']),
patItem('Hollow square', 'stars on the border only', {
code: n => PY(n, `for i in range(n):\n for j in range(n):\n if i == 0 or i == n - 1 or j == 0 or j == n - 1:\n print("*", end="")\n else:\n print(" ", end="")\n print()`),
cols: ['row i', 'edge row?', 'prints'],
rows: n => Array.from({length:n}, (_, i) => { const edge = i === 0 || i === n - 1;
return {i, line:8, text:edge ? RP('*', n) : '*' + RP(' ', n - 2) + '*', cols:[i, edge ? 'yes' : 'no', edge ? `${n} stars` : '* gap *'], vars:{i, j:n - 1}}; }),
cap: (r, k, n) => k === 0 ? 'Every cell is either a star or a space, decided by an <code>if</code>. Row 0 is the top edge, so every cell is a star.' : r.i === n - 1 ? `<code>i == n − 1</code>: the bottom edge, all stars again.` : `Middle row <code>i = ${r.i}</code>: only <code>j == 0</code> and <code>j == n − 1</code> are edges, so stars at both ends and spaces between.`,
done: n => 'The condition is the whole trick: “is this cell on the border?”. Change it and you get other shapes, like an X or a frame.',
}, [['What decides star or space?', 'Whether the cell is on the first or last row, or the first or last column.'],
['How would you draw the diagonals (an X)?', 'Print a star when <code>j == i or j == n − 1 − i</code>.'],
['Why <code>range(n)</code> here instead of <code>range(1, n + 1)</code>?', 'Starting at 0 makes the edge checks simply 0 and <code>n − 1</code>.']],
['Shortcut: print the full row for edges, and <code>"*" + " " * (n - 2) + "*"</code> for the middle rows.',
'For n = 1 the formula breaks (" " * −1 is just empty); handle tiny sizes separately.',
'Many grid problems (boards, matrices) use this same “check i and j” idea.']),
patItem('Hollow pyramid', 'pyramid outline', {
code: n => PY(n, `for i in range(1, n + 1):\n for s in range(n - i):\n print(" ", end="")\n for j in range(2 * i - 1):\n if j == 0 or j == 2 * i - 2 or i == n:\n print("*", end="")\n else:\n print(" ", end="")\n print()`),
cols: ['row i', 'spaces', 'width', 'inside'],
rows: n => pyramidRows(n, up(n), 10, (i, st) => { if(n - i > 0) st.s = n - i - 1;
const body = i === n ? RP('*', 2 * n - 1) : i === 1 ? '*' : '*' + RP(' ', 2 * i - 3) + '*';
return {text:RP(' ', n - i) + body, cols:[i, n - i, 2 * i - 1, i === n ? 'filled base' : i === 1 ? 'single *' : 'hollow'], vars:Object.assign({}, 's' in st ? {s:st.s} : {}, {j:2 * i - 2})}; }),
cap: (r, k, n) => k === 0 ? 'Same spaces and width as the pyramid, but each position asks: is it the <b>first</b>, the <b>last</b>, or on the <b>base</b> row?' : r.i === n ? '<code>i == n</code>: the base is filled completely.' : `<code>i = ${r.i}</code>: star at <code>j = 0</code> and <code>j = ${2 * r.i - 2}</code>, spaces between.`,
done: n => 'Pyramid layout + hollow-square condition = hollow pyramid. Combining known pieces is how most pattern questions are solved.',
}, [['How is this built from earlier patterns?', 'The pyramid gives the spaces and width; the hollow square gives the “edge only” condition.'],
['What’s the last index in row i?', '<code>2i − 2</code>, because the row has <code>2i − 1</code> positions starting at 0.'],
['How would you make the base hollow too?', 'Drop <code>or i == n</code> from the condition.']],
['Trailing spaces inside the row are printed but invisible; they’re shown as dots here.',
'Test with n = 1 and n = 2, the usual edge cases.',
'A hollow diamond is this plus an inverted hollow half.']),
patItem('Number triangle', '1, 12, 123', {
code: n => PY(n, `for i in range(1, n + 1):\n for j in range(1, i + 1):\n print(j, end="")\n print()`),
cols: ['row i', 'prints'],
rows: n => pyramidRows(n, up(n), 5, i => { const t = up(i).join(''); return {text:t, cols:[i, t], vars:{j:i}}; }),
cap: (r, k, n) => k === 0 ? 'Same shape as the star triangle, but the inner loop prints <code>j</code> itself. It starts at 1, so <code>range(1, i + 1)</code>.' : `<code>i = ${r.i}</code>: <code>j</code> runs 1 to ${r.i}.`,
done: n => 'Swapping <code>"*"</code> for the loop variable is all it takes to turn a star pattern into a number pattern.',
}, [['Why <code>range(1, i + 1)</code>?', 'To print 1 to i inclusive; the stop value is excluded, so it must be i + 1.'],
['What about numbers 10 and above?', 'They take two characters, so columns stop lining up. Use <code>print(f"{j:3}", end="")</code> to pad.'],
['Shortcut?', '<code>print("".join(str(j) for j in range(1, i + 1)))</code>.']],
['<code>print(j, end="")</code> works with ints; no need to convert to str.',
'Printing <code>i</code> instead of <code>j</code> gives the next pattern (1, 22, 333).',
'Printing <code>j</code> with <code>end=" "</code> spaces the numbers out.']),
patItem('Repeated number rows', '1, 22, 333', {
code: n => PY(n, `for i in range(1, n + 1):\n for j in range(i):\n print(i, end="")\n print()`),
cols: ['row i', 'prints'],
rows: n => pyramidRows(n, up(n), 5, i => ({text:RP(String(i), i), cols:[i, `${i}, ${i} time${i > 1 ? 's' : ''}`], vars:{j:i - 1}})),
cap: (r, k, n) => k === 0 ? 'Here the inner loop only counts; it prints the <b>row</b> number <code>i</code>, not <code>j</code>.' : `<code>i = ${r.i}</code>: the digit ${r.i}, printed ${r.i} times.`,
done: n => 'Compare with the number triangle: the only difference is printing <code>i</code> instead of <code>j</code>.',
}, [['What’s the difference from 1, 12, 123?', 'Printing <code>i</code> (the row) instead of <code>j</code> (the position).'],
['Shortcut?', '<code>print(str(i) * i)</code>.'],
['How would you get 1, 21, 321?', 'Inner loop <code>for j in range(i, 0, -1): print(j, end="")</code>.']],
['<code>str(i) * i</code> repeats the text, it doesn’t multiply numbers.',
'Ask yourself which variable changes along a row: that’s the one to print.',
'Same idea with letters gives A, BB, CCC.']),
patItem("Floyd's triangle", '1 / 2 3 / 4 5 6', {
code: n => PY(n, `num = 1\nfor i in range(1, n + 1):\n for j in range(i):\n print(num, end=" ")\n num += 1\n print()`),
init: {line:2, cap:'A counter <code>num</code> lives <b>outside</b> both loops, so it keeps counting across rows instead of restarting.', vars:[['num', 1]]},
cols: ['row i', 'numbers', 'num after'],
rows: n => { let num = 1; return up(n).map(i => { const nums = Array.from({length:i}, () => num++);
return {i, line:7, text:nums.map(x => x + ' ').join(''), cols:[i, nums.length > 1 ? `${nums[0]} – ${nums[nums.length - 1]}` : String(nums[0]), num], vars:{i, j:i - 1, num}}; }); },
cap: (r, k, n) => k === 0 ? 'Row 1 prints one number, then <code>num += 1</code> makes it 2. <code>end=" "</code> adds a space after each number (a trailing dot is visible).' : `<code>i = ${r.i}</code>: ${r.i} numbers, continuing from where the last row stopped.`,
done: n => `The last number is <code>n(n + 1) / 2 = ${n * (n + 1) / 2}</code>. Floyd’s triangle is a classic for testing whether someone puts the counter in the right place.`,
}, [['Where must <code>num</code> be initialised?', 'Before the outer loop. Inside it, every row would restart at 1.'],
['What is the last number printed?', '<code>n(n + 1) / 2</code>, the n-th triangular number.'],
['How do you keep columns aligned when numbers get two digits?', 'Pad them: <code>print(f"{num:3}", end="")</code>.']],
['<code>end=" "</code> leaves a trailing space at the end of each row; harmless on screen, but it matters if output is compared exactly.',
'Use <code>" ".join(...)</code> per row to avoid that trailing space.',
'Columns drift once numbers reach 10, since 10 takes two characters.']),
patItem('Number palindrome pyramid', '1, 121, 12321', {
code: n => PY(n, `for i in range(1, n + 1):\n for s in range(n - i):\n print(" ", end="")\n for j in range(1, i + 1):\n print(j, end="")\n for j in range(i - 1, 0, -1):\n print(j, end="")\n print()`),
cols: ['row i', 'spaces', 'up', 'down'],
rows: n => pyramidRows(n, up(n), 9, (i, st) => { if(n - i > 0) st.s = n - i - 1; const u = up(i).join(''), d = down(i - 1).join('');
return {text:RP(' ', n - i) + u + d, cols:[i, n - i, u, d || '—'], vars:Object.assign({}, 's' in st ? {s:st.s} : {}, {j:i > 1 ? 1 : i})}; }),
cap: (r, k, n) => k === 0 ? 'Three inner loops: spaces, then counting <b>up</b> 1 → i, then counting <b>down</b> i − 1 → 1. Row 1 has nothing to count down.' : `<code>i = ${r.i}</code>: up to ${r.i}, back down to 1. Reads the same both ways.`,
done: n => 'Up-then-down without repeating the peak is the key idea: the second loop starts at <code>i − 1</code>.',
}, [['Why does the down loop start at <code>i − 1</code>?', 'So the peak digit i isn’t printed twice.'],
['How many characters per row (excluding spaces)?', '<code>2i − 1</code>, the same as the star pyramid.'],
['Up to what n does this look right?', 'n = 9. From 10, two-digit numbers break the symmetry.']],
['Shortcut: <code>"".join(map(str, range(1, i + 1))) + "".join(map(str, range(i - 1, 0, -1)))</code>.',
'Fun fact: 1, 121, 12321 are 1², 11², 111².',
'Swap digits for letters and you get the alphabet pyramid.']),
patItem('Letter triangle', 'A, AB, ABC', {
code: n => PY(n, `for i in range(1, n + 1):\n for j in range(i):\n print(chr(65 + j), end="")\n print()`),
cols: ['row i', 'letters'],
rows: n => pyramidRows(n, up(n), 5, i => { const t = Array.from({length:i}, (_, j) => L(j)).join(''); return {text:t, cols:[i, t], vars:{j:i - 1}}; }),
cap: (r, k, n) => k === 0 ? '<code>chr()</code> turns a character code into a letter. Code 65 is <code>"A"</code>, 66 is <code>"B"</code>, and so on, so <code>chr(65 + j)</code> walks through the alphabet.' : `<code>i = ${r.i}</code>: <code>j</code> = 0 to ${r.i - 1} gives A to ${L(r.i - 1)}.`,
done: n => 'Letters are just numbers underneath. <code>ord("A")</code> goes the other way and gives 65.',
}, [['What do <code>chr</code> and <code>ord</code> do?', '<code>chr(65)</code> → "A"; <code>ord("A")</code> → 65. They convert between characters and their Unicode code points.'],
['How do you get lowercase letters?', 'Start at 97: <code>chr(97 + j)</code>, or use <code>string.ascii_lowercase[j]</code>.'],
['Without <code>chr</code>?', '<code>import string</code> and slice: <code>print(string.ascii_uppercase[:i])</code>.']],
['<code>ord("A") + j</code> is clearer than the magic number 65.',
'Past 26 rows you run out of letters; <code>chr(91)</code> is “[”.',
'This is the number triangle with digits swapped for letters.']),
patItem('Repeated letter rows', 'A, BB, CCC', {
code: n => PY(n, `for i in range(1, n + 1):\n for j in range(i):\n print(chr(64 + i), end="")\n print()`),
cols: ['row i', 'chr(64 + i)', 'letter'],
rows: n => pyramidRows(n, up(n), 5, i => ({text:RP(L(i - 1), i), cols:[i, `chr(${64 + i})`, L(i - 1)], vars:{j:i - 1}})),
cap: (r, k, n) => k === 0 ? 'The letter depends on the <b>row</b>, not the position: <code>chr(64 + i)</code>. Row 1 → code 65 → A.' : `<code>i = ${r.i}</code>: code ${64 + r.i} is ${L(r.i - 1)}, printed ${r.i} times.`,
done: n => 'Same structure as 1, 22, 333, with the row number turned into a letter.',
}, [['Why <code>64 + i</code> and not <code>65 + i</code>?', '<code>i</code> starts at 1, and row 1 must be A (65).'],
['Shortcut?', '<code>print(chr(64 + i) * i)</code>.'],
['How would you get A, BA, CBA?', 'Inner loop counting down: <code>for j in range(i, 0, -1): print(chr(64 + j), end="")</code>.']],
['When a pattern repeats one value per row, print the outer variable.',
'Off-by-one between 64 and 65 is the classic bug here.',
'Write the first row by hand and check which code you need.']),
patItem('Alphabet pyramid', 'A, ABA, ABCBA', {
code: n => PY(n, `for i in range(1, n + 1):\n for s in range(n - i):\n print(" ", end="")\n for j in range(i):\n print(chr(65 + j), end="")\n for j in range(i - 2, -1, -1):\n print(chr(65 + j), end="")\n print()`),
cols: ['row i', 'spaces', 'up', 'down'],
rows: n => pyramidRows(n, up(n), 9, (i, st) => { if(n - i > 0) st.s = n - i - 1;
const u = Array.from({length:i}, (_, j) => L(j)).join(''), d = Array.from({length:i - 1}, (_, j) => L(i - 2 - j)).join('');
return {text:RP(' ', n - i) + u + d, cols:[i, n - i, u, d || '—'], vars:Object.assign({}, 's' in st ? {s:st.s} : {}, {j:0})}; }),
cap: (r, k, n) => k === 0 ? 'The palindrome pyramid with letters: spaces, then A up to the row’s letter, then back down. Row 1 is just A.' : `<code>i = ${r.i}</code>: up to ${L(r.i - 1)}, then back down to A.`,
done: n => `Every concept here combined: spaces from the pyramid, up-and-down from the palindrome, letters from <code>chr</code>. The widest row has <code>2n − 1 = ${2 * n - 1}</code> letters.`,
}, [['Why does the down loop use <code>range(i − 2, −1, −1)</code>?', 'It counts j from i − 2 down to 0, so the peak letter (index i − 1) isn’t repeated and it ends at A (index 0).'],
['How is this related to the number palindrome?', 'Same structure; <code>chr(65 + j)</code> replaces the digit.'],
['Shortcut?', 'Build <code>up = string.ascii_uppercase[:i]</code> and print <code>" " * (n - i) + up + up[-2::-1]</code>.']],
['<code>up[-2::-1]</code> reverses the string, skipping its last letter.',
'Breaking a pattern into small loops (spaces, up, down) keeps it easy to debug.',
'Interviewers often ask to explain the formula table before writing code.']),
]];
const EXAMPLES = [
['1. Python Fundamentals', 'The building blocks', [
['Variables & data types', 'Names that point to values',
`age = 25
price = 99.5
name = "Asha"
is_member = True
age = 26
print(type(price))`,
() => trace(step => {
step(1, 'Python creates an <code>int</code> object holding 25 and binds the name <code>age</code> to it. You never declare a type; the value decides it.',
n => { obj(n, 'V1', {t:'int', v:25}); set(n, 'age', {ref:'V1'}); });
step(2, 'A number with a decimal point becomes a <code>float</code>.',
n => { obj(n, 'V2', {t:'float', v:99.5}); set(n, 'price', {ref:'V2'}); });
step(3, 'Text inside quotes is a <code>str</code>.',
n => { obj(n, 'V3', {t:'str', v:'Asha'}); set(n, 'name', {ref:'V3'}); });
step(4, '<code>True</code> and <code>False</code> are <code>bool</code> values. The capital letter matters.',
n => { obj(n, 'V4', {t:'bool', v:true}); set(n, 'is_member', {ref:'V4'}); });
step(5, 'Rebinding: <code>age</code> now points to a new object, 26. Nothing refers to 25 any more, so Python will clean it up.',
n => { n.objs.V1.gone = true; obj(n, 'V5', {t:'int', v:26}); set(n, 'age', {ref:'V5'}); });
step(6, '<code>type()</code> tells you what kind of object a name points to.',
n => { delete n.objs.V1; out(n, "<class 'float'>"); });
}),
[['Do you declare variable types in Python?', 'No. Python is dynamically typed: the object carries the type, and a name can point to an object of any type.'],
['What does a variable actually store?', 'A reference to an object. The object has the type and value; the name is just a label pointing at it.'],
['What are the naming rules for variables?', 'Letters, digits and underscores, not starting with a digit, and not a keyword like <code>if</code>. By convention use <code>snake_case</code>.']],
['Names are case-sensitive: <code>Age</code> and <code>age</code> are different variables.',
'<code>True</code>, <code>False</code> and <code>None</code> must be capitalised.',
'Use <code>type(x)</code> or <code>isinstance(x, int)</code> to check a type.']],
['int, float, str, bool', 'What each type can do',
`count = 7 // 2
ratio = 7 / 2
word = "ab" * 3
flag = 7 > 2
print(count, ratio, word, flag)`,
() => trace(step => {
step(1, '<code>//</code> is floor division. With two ints, the result stays an <code>int</code>.',
n => { expr(n, '7 // 2', '3'); set(n, 'count', 3); });
step(2, '<code>/</code> always returns a <code>float</code>, even when it divides evenly (<code>8 / 2</code> is <code>4.0</code>).',
n => { expr(n, '7 / 2', '3.5'); set(n, 'ratio', 3.5); });
step(3, 'Multiplying a <code>str</code> by an <code>int</code> repeats the text.',
n => { expr(n, '"ab" * 3', "'ababab'"); set(n, 'word', 'ababab'); });
step(4, 'A comparison always produces a <code>bool</code>.',
n => { expr(n, '7 > 2', 'True'); set(n, 'flag', true); });
step(5, '<code>print</code> turns each value into text and separates them with spaces.',
n => out(n, '3 3.5 ababab True'));
}),
[['Why does <code>0.1 + 0.2</code> not equal <code>0.3</code>?', 'Floats are stored in binary and can’t represent 0.1 exactly, so the sum is 0.30000000000000004. Use <code>round()</code>, <code>math.isclose()</code> or <code>decimal.Decimal</code>.'],
['Is <code>bool</code> a kind of <code>int</code>?', 'Yes. <code>bool</code> is a subclass of <code>int</code>, so <code>True + True</code> is 2.'],
['Are Python strings mutable?', 'No. Every string operation returns a new string; the original never changes.']],
['Python ints have no size limit, so <code>2 ** 100</code> just works.',
'<code>//</code> rounds down, not towards zero: <code>-7 // 2</code> is <code>-4</code>.',
'Mixing an int and a float gives a float: <code>1 + 2.0</code> is <code>3.0</code>.']],
['Type casting', 'Converting between types',
`text = "42"
num = int(text)
total = num + 8
price = float("19.99")
label = str(total) + " items"
empty = bool("")`,
() => trace(step => {
step(1, 'This looks like a number, but the quotes make it a <code>str</code>.',
n => set(n, 'text', '42'));
step(2, '<code>int()</code> reads the text and builds a real <code>int</code>.',
n => { expr(n, 'int(text)', 'int("42")', '42'); set(n, 'num', 42); });
step(3, 'Now maths works. <code>"42" + 8</code> would have raised a <code>TypeError</code>.',
n => { expr(n, 'num + 8', '42 + 8', '50'); set(n, 'total', 50); });
step(4, '<code>float()</code> converts text with a decimal point.',
n => { expr(n, 'float("19.99")', '19.99'); set(n, 'price', 19.99); });
step(5, 'To join text and a number, convert the number to <code>str</code> first.',
n => { expr(n, 'str(total) + " items"', '"50" + " items"', "'50 items'"); set(n, 'label', '50 items'); });
step(6, 'An empty string is falsy, so <code>bool("")</code> is <code>False</code>. Any non-empty string, even <code>"False"</code>, gives <code>True</code>.',
n => { expr(n, 'bool("")', 'False'); set(n, 'empty', false); });
}),
[['Implicit vs explicit conversion?', 'Implicit happens automatically, like <code>1 + 2.0</code> becoming a float. Explicit is when you call <code>int()</code>, <code>float()</code> or <code>str()</code> yourself.'],
['What does <code>int("4.5")</code> do?', 'It raises <code>ValueError</code>. Use <code>int(float("4.5"))</code>, which gives 4.'],
['Which values are falsy?', '<code>0</code>, <code>0.0</code>, <code>""</code>, <code>None</code>, <code>False</code> and empty collections like <code>[]</code>, <code>{}</code>, <code>()</code>.']],
['<code>int(3.9)</code> cuts off the decimal and gives 3. It does not round.',
'<code>bool("False")</code> is <code>True</code>, because the string isn’t empty.',
'Wrap conversions of user input in <code>try</code>/<code>except ValueError</code>.']],
['Operators', 'Arithmetic, comparison, logical',
`a = 10
b = 3
total = a + b * 2
rem = a % b
power = b ** 2
check = a > 5 and b > 5
print(total, rem, power, check)`,
() => trace(step => {
step(1, '<code>a</code> is 10.', n => set(n, 'a', 10));
step(2, '<code>b</code> is 3.', n => set(n, 'b', 3));
step(3, '<code>*</code> runs before <code>+</code>, just like in maths. Use brackets to change the order.',
n => { expr(n, 'a + b * 2', '10 + 3 * 2', '10 + 6', '16'); set(n, 'total', 16); });
step(4, '<code>%</code> gives the remainder after division.',
n => { expr(n, 'a % b', '10 % 3', '1'); set(n, 'rem', 1); });
step(5, '<code>**</code> raises to a power.',
n => { expr(n, 'b ** 2', '3 ** 2', '9'); set(n, 'power', 9); });
step(6, 'Comparisons run first, then <code>and</code>. It needs both sides True, so the result is False.',
n => { expr(n, 'a > 5 and b > 5', 'True and b > 5', 'True and False', 'False'); set(n, 'check', false); });
step(7, 'All four results are printed.', n => out(n, '16 1 9 False'));
}),
[['What is operator precedence?', 'The order operators run in: <code>**</code>, then <code>* / // %</code>, then <code>+ -</code>, then comparisons, then <code>not</code>, <code>and</code>, <code>or</code>.'],
['What is short-circuit evaluation?', '<code>and</code> stops at the first falsy value and <code>or</code> at the first truthy one, so the right side may never run.'],
['<code>==</code> vs <code>is</code>?', '<code>==</code> compares values; <code>is</code> checks if both sides are the same object.']],
['<code>and</code>/<code>or</code> return one of the operands, not always a bool: <code>0 or "hi"</code> is <code>"hi"</code>.',
'<code>**</code> groups from the right: <code>2 ** 3 ** 2</code> is <code>2 ** 9</code>.',
'Shortcuts like <code>x += 1</code> exist, but there’s no <code>x++</code> in Python.']],
['Input / Output', 'input() and print()',
`name = input("Your name: ")
age = int(input("Your age: "))
print("Hello,", name)
print(f"Next year you'll be {age + 1}")`,
() => trace(step => {
step(1, '<code>input()</code> shows the prompt and waits. The user types <code>Asha</code>, and it comes back as a <code>str</code>.',
n => { out(n, {p:'Your name: ', typed:'Asha'}); set(n, 'name', 'Asha'); });
step(2, '<code>input()</code> always returns a <code>str</code>, even for digits. Wrapping it in <code>int()</code> converts it.',
n => { out(n, {p:'Your age: ', typed:'25'}); expr(n, 'int(input("Your age: "))', 'int("25")', '25'); set(n, 'age', 25); });
step(3, '<code>print</code> puts a space between comma-separated values.',
n => out(n, 'Hello, Asha'));
step(4, 'An f-string runs the expression in braces and drops the result into the text.',
n => { expr(n, 'age + 1', '26'); out(n, "Next year you'll be 26"); });
}),
[['What type does <code>input()</code> return?', 'Always <code>str</code>. Convert it with <code>int()</code> or <code>float()</code> for maths.'],
['How do you print without a newline?', 'Pass <code>end</code>: <code>print("Hi", end="")</code>. Use <code>sep</code> to change the separator between values.'],
['How do you read several numbers on one line?', '<code>a, b = map(int, input().split())</code>.']],
['Typed values are shown in green in the output panel; in a real terminal you type them.',
'<code>print()</code> returns <code>None</code>. Don’t write <code>x = print(...)</code>.',
'Prefer f-strings over joining with <code>+</code>; they handle non-str values for you.']],
['Comments', 'Notes Python ignores',
`# Price after a 10% discount
price = 200
discount = 0.1 # 10 percent
final = price * (1 - discount)
"""A bare string like this is
created and then thrown away."""
print(final)`,
() => trace(step => {
step(1, 'Lines starting with <code>#</code> are comments. Python skips them, so memory doesn’t change.', null);
step(2, '<code>price</code> is 200.', n => set(n, 'price', 200));
step(3, 'Everything after <code>#</code> on a line is ignored too, so only <code>discount = 0.1</code> runs.', n => set(n, 'discount', 0.1));
step(4, 'Brackets run first. An int times a float gives a float.',
n => { expr(n, 'price * (1 - discount)', '200 * (1 - 0.1)', '200 * 0.9', '180.0'); set(n, 'final', F(180)); });
step(5, 'Python has no multi-line comment syntax. A triple-quoted string on its own line is created and discarded, so it works like one.',
n => { n.block = [5, 6]; });
step(7, 'Only the code ran; the comments left no trace.', n => out(n, '180.0'));
}),
[['Does Python have multi-line comments?', 'No. Use several <code>#</code> lines. A triple-quoted string works, but it’s really a string, not a comment.'],
['What is a docstring?', 'A string as the first statement of a function, class or module. Python stores it in <code>__doc__</code>, and <code>help()</code> shows it.'],
['What makes a good comment?', 'One that explains why the code does something. The code itself should show what it does.']],
['Comments cost nothing at runtime.',
'A <code>#</code> inside quotes is just a character: <code>"#1"</code> is a string.',
'Most editors toggle comments with Ctrl + /.']],
['Indentation', 'How Python groups code',
`temp = 32
if temp > 30:
print("It's hot")
advice = "Drink water"
print("Done")`,
() => trace(step => {
step(1, '<code>temp</code> is 32.', n => set(n, 'temp', 32));
step(2, 'The condition is True. The indented lines below form the <code>if</code> block, shaded in the code.',
n => { expr(n, 'temp > 30', '32 > 30', 'True'); n.block = [3, 4]; });
step(3, 'The first line of the block runs.', n => { out(n, "It's hot"); n.block = [3, 4]; });
step(4, 'Still indented, so still inside the block.', n => { set(n, 'advice', 'Drink water'); n.block = [3, 4]; });
step(5, 'Back at the left edge: this line is outside the <code>if</code> and runs whatever <code>temp</code> is.', n => out(n, 'Done'));
}),
[['Why does Python use indentation?', 'It replaces curly braces. The indentation is the structure, so code always looks the way it runs.'],
['What causes <code>IndentationError</code>?', 'Uneven indentation in one block, or a missing indented line after a colon.'],
['Tabs or spaces?', 'Four spaces, as PEP 8 recommends. Mixing tabs and spaces raises <code>TabError</code> in Python 3.']],
['Every line ending in <code>:</code> needs an indented block after it.',
'An empty block needs <code>pass</code> to be valid.',
'Variables made inside an <code>if</code> block still exist after it; blocks don’t create scope.']],
]],