-
Notifications
You must be signed in to change notification settings - Fork 0
/
atom.xml
531 lines (249 loc) · 421 KB
/
atom.xml
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
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Siz Long</title>
<link href="https://longsizhuo.github.io/atom.xml" rel="self"/>
<link href="https://longsizhuo.github.io/"/>
<updated>2024-10-28T11:02:10.175Z</updated>
<id>https://longsizhuo.github.io/</id>
<author>
<name>loong loong</name>
</author>
<generator uri="https://hexo.io/">Hexo</generator>
<entry>
<title>9021_TUT_7</title>
<link href="https://longsizhuo.github.io/post/891330b3.html"/>
<id>https://longsizhuo.github.io/post/891330b3.html</id>
<published>2024-10-28T16:00:39.531Z</published>
<updated>2024-10-28T11:02:10.175Z</updated>
<content type="html"><![CDATA[<h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="what-is-yield-in-python"><a href="#what-is-yield-in-python" class="headerlink" title="what is yield in python?"></a>what is <code>yield</code> in python?</h3><p>The yield keyword in Python is used to create generator functions. A generator function is a special kind of function that returns a generator iterator, which can be used to iterate over a sequence of values. Unlike a regular function that returns a single value using the return statement, a generator function can yield multiple values, one at a time, pausing its state between each one.</p><h3 id="How-it-works"><a href="#How-it-works" class="headerlink" title="How it works?"></a>How it works?</h3><p>When a generator function is called, it doesn’t execute its code immediately. Instead, it returns a generator object that can be iterated over. Each time you request the next item from the generator (using next() or a loop), the generator function resumes execution from where it last left off, runs until it hits a yield statement, and yields the value to the caller.</p><h3 id="Problem-Description"><a href="#Problem-Description" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>First, we need to understand the requirements of the problem:</p><p>Input: A list of integers L, such as [n1, n2, n3, …]. Output:</p><ul><li>Output n1 lines of rank 1 X, which means X without indentation.</li><li>Between each pair of rank 1 X, output n2 lines of rank 2 X, which are indented with one tab (\t).</li><li>Between each pair of rank 2 X, output n3 lines of rank 3 X, which are indented with two tabs.</li><li>Continue this pattern until all elements in the list L have been processed.</li></ul><h3 id="My-solution"><a href="#My-solution" class="headerlink" title="My solution"></a>My solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>():</span><br><span class="line"> <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">" /\\"</span>)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">"/ \\"</span>)</span><br><span class="line"> <span class="keyword">yield</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">"----"</span>)</span><br><span class="line"> <span class="keyword">yield</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">"\\ /"</span>)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">" \\/"</span>)</span><br><span class="line"> <span class="keyword">yield</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">" ||"</span>)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">" ||"</span>)</span><br><span class="line"> <span class="keyword">yield</span></span><br></pre></td></tr></table></figure><h3 id="Standard-solution"><a href="#Standard-solution" class="headerlink" title="Standard solution"></a>Standard solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>():</span><br><span class="line"> <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">' /\\\n/ \\'</span>)</span><br><span class="line"> <span class="keyword">yield</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'----'</span>)</span><br><span class="line"> <span class="keyword">yield</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'\\ /\n \\/'</span>)</span><br><span class="line"> <span class="keyword">yield</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">' ||\n ||'</span>)</span><br><span class="line"> <span class="keyword">yield</span></span><br></pre></td></tr></table></figure><h1 id="Exercise-2"><a href="#Exercise-2" class="headerlink" title="Exercise 2"></a>Exercise 2</h1><h3 id="Problem-Description-1"><a href="#Problem-Description-1" class="headerlink" title="Problem Description"></a>Problem Description</h3><figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Line: [1, 3, 3, 1]</span><br><span class="line"> | | |</span><br><span class="line"> i=0 i=1 i=2</span><br><span class="line"> ↓ ↓ ↓</span><br><span class="line">Calculate:1+3 3+3 3+1</span><br><span class="line"> ↓ ↓ ↓</span><br><span class="line">Results: 4 6 4</span><br></pre></td></tr></table></figure><h3 id="My-solution-1"><a href="#My-solution-1" class="headerlink" title="My solution"></a>My solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>():</span><br><span class="line"> <span class="comment"># initialized</span></span><br><span class="line"> row = [<span class="number">1</span>]</span><br><span class="line"> <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line"> <span class="keyword">yield</span> row</span><br><span class="line"> <span class="comment"># row[i] + row[i + 1] is the expression in list comprehension</span></span><br><span class="line"> row = [<span class="number">1</span>] + [row[i] + row[i + <span class="number">1</span>] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(row)-<span class="number">1</span>)] + [<span class="number">1</span>]</span><br></pre></td></tr></table></figure><h3 id="Standard-solution-1"><a href="#Standard-solution-1" class="headerlink" title="Standard solution"></a>Standard solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>():</span><br><span class="line"> L = [<span class="number">1</span>]</span><br><span class="line"> <span class="keyword">yield</span> L</span><br><span class="line"> <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line"> L = [<span class="number">1</span>] + [L[i] + L[i + <span class="number">1</span>] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(L) - <span class="number">1</span>)] + [<span class="number">1</span>]</span><br><span class="line"> <span class="keyword">yield</span> L</span><br></pre></td></tr></table></figure><h1 id="Exercise-3"><a href="#Exercise-3" class="headerlink" title="Exercise 3"></a>Exercise 3</h1><h3 id="Problem-Description-2"><a href="#Problem-Description-2" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>First, we need to understand the requirements of the problem:</p><p>Input: A list of integers L, such as [n1, n2, n3, …]. Output:</p><ul><li>Output n1 lines of <strong>rank 1</strong> X, which means X without indentation.</li><li>Between each pair of <strong>rank 1</strong> X, output n2 lines of <strong>rank 2</strong> X, which are indented with one tab (\t).</li><li>Between each pair of <strong>rank 2</strong> X, output n3 lines of <strong>rank 3</strong> X, which are indented with two tabs.</li><li>Continue this pattern until all elements in the list L have been processed.</li></ul><h3 id="My-solution-2"><a href="#My-solution-2" class="headerlink" title="My solution"></a>My solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">L</span>):</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">helper</span>(<span class="params">L, rank</span>):</span><br><span class="line"> <span class="keyword">if</span> <span class="keyword">not</span> L:</span><br><span class="line"> <span class="keyword">return</span></span><br><span class="line"> n = L[<span class="number">0</span>]</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'\t'</span> * rank + <span class="string">'X'</span>)</span><br><span class="line"> <span class="keyword">if</span> i < n - <span class="number">1</span>:</span><br><span class="line"> helper(L[<span class="number">1</span>:], rank + <span class="number">1</span>)</span><br><span class="line"> helper(L, <span class="number">0</span>)</span><br></pre></td></tr></table></figure><p>We need to write a recursive function to handle this nested structure. Here is the implementation idea:</p><p>Define a helper function <code>helper(L, rank)</code>, where:</p><ul><li><code>L</code> is the list currently being processed.</li><li><code>rank</code> is the current level (indentation level).</li></ul><p>In the <code>helper</code> function:</p><ol><li>If the list is empty, return directly.</li><li>Get the number of lines to output at the current level, <code>n = L[0]</code>.</li><li>Use a loop to output <code>n</code> lines of the current level’s X, with each line having the corresponding number of tab characters (<code>\t</code>) based on the <code>rank</code>.</li><li>After each output, if it is not the last element and it is not the last line, recursively call <code>helper</code> to handle the next level of <code>X</code> lines.</li></ol><h3 id="Standard-solution-2"><a href="#Standard-solution-2" class="headerlink" title="Standard solution"></a>Standard solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">L</span>):</span><br><span class="line"> _f3(L, <span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">_f3</span>(<span class="params">L, n</span>):</span><br><span class="line"> <span class="keyword">if</span> n == <span class="built_in">len</span>(L):</span><br><span class="line"> <span class="keyword">return</span></span><br><span class="line"> <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(L[n] - <span class="number">1</span>):</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'\t'</span> * n, <span class="string">'X'</span>, sep=<span class="string">''</span>)</span><br><span class="line"> _f3(L, n + <span class="number">1</span>)</span><br><span class="line"> <span class="keyword">if</span> L[n]:</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'\t'</span> * n, <span class="string">'X'</span>, sep=<span class="string">''</span>)</span><br></pre></td></tr></table></figure><h1 id="Exercise-4"><a href="#Exercise-4" class="headerlink" title="Exercise 4"></a>Exercise 4</h1><h3 id="Problem-Description-3"><a href="#Problem-Description-3" class="headerlink" title="Problem Description"></a>Problem Description</h3><p><strong>Objective:</strong> Given a list <code>L</code> of integers, we need to:</p><ul><li>Break it down into sublists of <strong>equal length</strong>, where the <strong>length is maximal</strong>.</li><li>This process is <strong>recursive</strong>: each sublist is further broken down in the same manner.</li><li>The original list should be <strong>preserved</strong> (i.e., not modified).</li></ul><p><strong>Key Points:</strong></p><ul><li>We aim to split the list into the largest possible sublists of equal length (greater than 1) that evenly divide the length of the list.</li><li>The recursion continues until a sublist cannot be broken down further (i.e., its length cannot be divided into equal parts greater than 1).</li></ul><h3 id="My-solution-3"><a href="#My-solution-3" class="headerlink" title="My solution"></a>My solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> math <span class="keyword">import</span> sqrt</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">L</span>):</span><br><span class="line"> n = <span class="built_in">len</span>(L)</span><br><span class="line"> <span class="comment"># Try to find the maximal sublist length greater than 1</span></span><br><span class="line"> <span class="keyword">for</span> sublist_length <span class="keyword">in</span> <span class="built_in">range</span>(n // <span class="number">2</span>, <span class="number">1</span>, -<span class="number">1</span>):</span><br><span class="line"> <span class="keyword">if</span> n % sublist_length == <span class="number">0</span>:</span><br><span class="line"> <span class="comment"># Split the list into sublists</span></span><br><span class="line"> sublists = [f4(L[i:i + sublist_length]) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, n, sublist_length)]</span><br><span class="line"> <span class="keyword">return</span> sublists</span><br><span class="line"> <span class="keyword">return</span> L.copy()</span><br></pre></td></tr></table></figure><h3 id="Standard-solution-3"><a href="#Standard-solution-3" class="headerlink" title="Standard solution"></a>Standard solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">L</span>):</span><br><span class="line"> <span class="keyword">for</span> n <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">2</span>, <span class="built_in">round</span>(sqrt(<span class="built_in">len</span>(L))) + <span class="number">1</span>):</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">len</span>(L) % n == <span class="number">0</span>:</span><br><span class="line"> w = <span class="built_in">len</span>(L) // n</span><br><span class="line"> <span class="keyword">return</span> [f4(L[i : i + w]) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, <span class="built_in">len</span>(L), w)]</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">list</span>(L)</span><br></pre></td></tr></table></figure><h1 id="Exercise-5"><a href="#Exercise-5" class="headerlink" title="Exercise 5"></a>Exercise 5</h1><h3 id="Problem-Description-4"><a href="#Problem-Description-4" class="headerlink" title="Problem Description"></a>Problem Description</h3><p><strong>Objective</strong>: Given a special list <code>L</code> (a list whose elements are integers or other special lists), we need to return a dictionary where:</p><p>Keys are tuples of indices <code>(i_1, i_2, ..., i_n)</code>.<br>Values are integers <code>e</code>.<br>The keys represent the path of indices to reach an integer <code>e</code> within the nested list structure.</p><p><strong>Interpretation</strong>:</p><ul><li>If the key is <code>(i_1,)</code>, then <code>L[i_1]</code> is an integer <code>e</code>.</li><li>If the key is <code>(i_1, i_2)</code>, then <code>L[i_1][i_2]</code> is an integer <code>e</code>.</li><li>If the key is <code>(i_1, i_2, i_3)</code>, then <code>L[i_1][i_2][i_3]</code> is an integer <code>e</code>.</li><li>And so on.</li></ul><p><strong>Constraints:</strong></p><p>We need to handle any depth of nesting.<br>Use <code>isinstance()</code> to check if an element is an integer or a list.<br>The original list should not be modified.</p><h3 id="My-solution-4"><a href="#My-solution-4" class="headerlink" title="My solution"></a>My solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">L</span>):</span><br><span class="line"> result = {}</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">helper</span>(<span class="params">sublist, path</span>):</span><br><span class="line"> <span class="keyword">for</span> index, element <span class="keyword">in</span> <span class="built_in">enumerate</span>(sublist):</span><br><span class="line"> current_path = path + (index,)</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">isinstance</span>(element, <span class="built_in">int</span>):</span><br><span class="line"> result[current_path] = element</span><br><span class="line"> <span class="keyword">elif</span> <span class="built_in">isinstance</span>(element, <span class="built_in">list</span>):</span><br><span class="line"> helper(element, current_path)</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> <span class="comment"># If there are other types, you might want to handle them or raise an error</span></span><br><span class="line"> <span class="keyword">pass</span></span><br><span class="line"> helper(L, ())</span><br><span class="line"> <span class="keyword">return</span> result</span><br></pre></td></tr></table></figure><h3 id="Standard-solution-4"><a href="#Standard-solution-4" class="headerlink" title="Standard solution"></a>Standard solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">L</span>):</span><br><span class="line"> D = {}</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(L)):</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">isinstance</span>(L[i], <span class="built_in">int</span>):</span><br><span class="line"> D[(i,)] = L[i]</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> E = f5(L[i])</span><br><span class="line"> <span class="keyword">for</span> s <span class="keyword">in</span> E:</span><br><span class="line"> D[i, *s] = E[s]</span><br><span class="line"> <span class="keyword">return</span> D</span><br></pre></td></tr></table></figure><h3 id="Difference-between-my-solution-and-the-standard-solution"><a href="#Difference-between-my-solution-and-the-standard-solution" class="headerlink" title="Difference between my solution and the standard solution"></a>Difference between my solution and the standard solution</h3><p><strong>My Solution</strong></p><ul><li>Uses a Helper Function (helper): Your solution defines an inner function helper(sublist, path) to handle the recursion.</li><li>Explicit Path Passing: The path variable, representing the current position in the nested list, is explicitly passed and updated at each recursive call.</li><li>State Encapsulation: By using a nested function, the state (path and result) is encapsulated within the f5 function’s scope.</li></ul><p><strong>Standard Solution</strong></p><ul><li>Direct Recursion: The standard solution directly calls f5(L[i]) recursively without using a helper function.</li><li>Implicit Path Construction: It constructs the path by combining the current index i with the indices from the recursive call (s) using tuple unpacking.</li><li>Dictionary Merging: After each recursive call, it merges the returned dictionary E into the current dictionary D.</li></ul><h1 id="Exercise-6"><a href="#Exercise-6" class="headerlink" title="Exercise 6"></a>Exercise 6</h1><h3 id="Problem-Description-5"><a href="#Problem-Description-5" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>The given problem is not strictly about the Fibonacci sequence, but it generalizes similar principles to a broader set of recursive relationships. In the problem, you’re asked to compute the n-th term of a series, where the series is defined by some initial terms (first_terms) and a set of recurrence factors (factors). The Fibonacci sequence is a special case of such a recurrence relation, where each term is the sum of the two preceding terms.</p><h3 id="My-solution-Wrong"><a href="#My-solution-Wrong" class="headerlink" title="My solution(Wrong)"></a>My solution(Wrong)</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">first_terms, factors, n</span>):</span><br><span class="line"> k = <span class="built_in">len</span>(first_terms) - <span class="number">1</span></span><br><span class="line"> sequence = first_terms.copy()</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># If n is within the initial terms, return it directly</span></span><br><span class="line"> <span class="keyword">if</span> n <= k:</span><br><span class="line"> <span class="keyword">return</span> sequence[n]</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Compute terms iteratively up to n</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(k + <span class="number">1</span>, n + <span class="number">1</span>):</span><br><span class="line"> xi = <span class="number">0</span></span><br><span class="line"> <span class="keyword">for</span> s <span class="keyword">in</span> <span class="built_in">range</span>(k + <span class="number">1</span>):</span><br><span class="line"> xi += factors[s] * sequence[i - k - <span class="number">1</span> + s]</span><br><span class="line"> sequence.append(xi)</span><br><span class="line"> </span><br><span class="line"> <span class="keyword">return</span> sequence[n]</span><br></pre></td></tr></table></figure><h3 id="Standard-solution-5"><a href="#Standard-solution-5" class="headerlink" title="Standard solution"></a>Standard solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">first_terms, factors, n</span>):</span><br><span class="line"> series = {i: first_terms[i] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(first_terms))}</span><br><span class="line"> _f6(factors, n, series)</span><br><span class="line"> <span class="keyword">return</span> series[n]</span><br><span class="line"> </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">_f6</span>(<span class="params">factors, n, series</span>):</span><br><span class="line"> <span class="keyword">if</span> n <span class="keyword">in</span> series:</span><br><span class="line"> <span class="keyword">return</span></span><br><span class="line"> x = <span class="number">0</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="built_in">len</span>(factors) + <span class="number">1</span>):</span><br><span class="line"> _f6(factors, n - i, series)</span><br><span class="line"> x += factors[-i] * series[n - i]</span><br><span class="line"> series[n] = x</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="what-is-yield-in-python"><a href=</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="Tutorial" scheme="https://longsizhuo.github.io/tags/Tutorial/"/>
<category term="9021" scheme="https://longsizhuo.github.io/tags/9021/"/>
<category term="Answer" scheme="https://longsizhuo.github.io/tags/Answer/"/>
</entry>
<entry>
<title>9021_TUT_6</title>
<link href="https://longsizhuo.github.io/post/31af57d6.html"/>
<id>https://longsizhuo.github.io/post/31af57d6.html</id>
<published>2024-10-22T05:10:12.990Z</published>
<updated>2024-10-22T13:02:25.054Z</updated>
<content type="html"><![CDATA[<h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="Problem-description"><a href="#Problem-description" class="headerlink" title="Problem description"></a>Problem description</h3><p>It is hard to find the pattern of the input and output. But through this example:</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">statements = 'from exercise_6_1 import f1; '\</span><br><span class="line"> 'L = [[4, 8], [6, 3, 0], [7]]; print(f1(L))'</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">%</span><span class="language-bash">%run_and_test python3 -c <span class="string">"<span class="variable">$statements</span>"</span></span></span><br><span class="line"></span><br><span class="line">'([0, 3, 4, 6, 7, 8], [[0, 3], [4, 6, 7], [8]])\n'</span><br></pre></td></tr></table></figure><p>We need to sort the elements into a one-dimensional list and then split them according to the lengths of the sublists in the input.</p><h3 id="My-Solution"><a href="#My-Solution" class="headerlink" title="My Solution"></a>My Solution</h3><p>So, the function <code>f1</code> should be like this:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">L</span>):</span><br><span class="line"> <span class="comment"># Calculate the length of each sublist</span></span><br><span class="line"> lengths = [<span class="built_in">len</span>(i) <span class="keyword">for</span> i <span class="keyword">in</span> L]</span><br><span class="line"> <span class="comment"># Split the list into a one-dimensional list</span></span><br><span class="line"> P = [i <span class="keyword">for</span> j <span class="keyword">in</span> L <span class="keyword">for</span> i <span class="keyword">in</span> j]</span><br><span class="line"> P.sort()</span><br><span class="line"> ans = []</span><br><span class="line"> flag = <span class="number">0</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(L)):</span><br><span class="line"> ans.append(P[flag: flag + lengths[i]])</span><br><span class="line"> flag += lengths[i]</span><br><span class="line"> <span class="keyword">return</span> P, ans</span><br></pre></td></tr></table></figure><h3 id="Standard-Solution"><a href="#Standard-Solution" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">L</span>):</span><br><span class="line"> lengths = [<span class="built_in">len</span>(L1) <span class="keyword">for</span> L1 <span class="keyword">in</span> L]</span><br><span class="line"> F = <span class="built_in">sorted</span>(e <span class="keyword">for</span> L1 <span class="keyword">in</span> L <span class="keyword">for</span> e <span class="keyword">in</span> L1)</span><br><span class="line"> R = []</span><br><span class="line"> i = <span class="number">0</span></span><br><span class="line"> <span class="keyword">for</span> n <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(L)):</span><br><span class="line"> R.append(F[i : (i := i + lengths[n])])</span><br><span class="line"> <span class="keyword">return</span> F, R</span><br></pre></td></tr></table></figure><h3 id="Explanation"><a href="#Explanation" class="headerlink" title="Explanation"></a>Explanation</h3><p>The difference between the two solutions is that the standard solution uses the walrus operator <code>:=</code> to simplify the code. The walrus operator is a new feature in Python 3.8. It is used to assign a value to a variable as part of an expression. It is useful when you want to assign a value to a variable and use that value in the same expression.</p><h1 id="Exercise-2"><a href="#Exercise-2" class="headerlink" title="Exercise 2"></a>Exercise 2</h1><h3 id="Problem-description-1"><a href="#Problem-description-1" class="headerlink" title="Problem description"></a>Problem description</h3><p>This exercise ask us to output the sum of diagonal elements of a matrix. Based on the line where <code>i</code>, <code>j</code> are located.<br>We can use <code>Numpy</code> to solve this problem. It has a function <code>numpy.diagonal()</code> that can return the diagonal elements of a matrix.</p><h3 id="My-Solution-1"><a href="#My-Solution-1" class="headerlink" title="My Solution"></a>My Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">L, i, j, major=<span class="literal">True</span></span>):</span><br><span class="line"> <span class="comment"># Convert L to a numpy array for easier indexing</span></span><br><span class="line"> L = np.array(L)</span><br><span class="line"> i -= <span class="number">1</span></span><br><span class="line"> j -= <span class="number">1</span></span><br><span class="line"> <span class="keyword">if</span> major:</span><br><span class="line"> dia = <span class="built_in">sum</span>(np.diag(L, k= j - i))</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> dia = <span class="built_in">sum</span>(np.diag(np.fliplr(L), k= (<span class="built_in">len</span>(L) - <span class="number">1</span> - j) - i))</span><br><span class="line"> <span class="keyword">return</span> dia</span><br></pre></td></tr></table></figure><h3 id="Explanation-1"><a href="#Explanation-1" class="headerlink" title="Explanation"></a>Explanation</h3><p>In a normal matrix, the <code>np.diag()</code> function allows extracting diagonals at different offsets, where the offset <code>k=0</code> represents the main diagonal.</p><p>When we flip the matrix, the coordinates for each cell change in such a way that we need to adjust our calculation of the offset accordingly.</p><p>Specifically, for a matrix of size <code>n</code>, flipping it means that the column index <code>j</code> of the original matrix transforms to <code>(n - 1 - j)</code> in the flipped version. Hence, when we want to calculate the offset of the diagonal that passes through <code>(i, j)</code> in the original matrix, we need to determine the offset using <code>(n - 1 - j) - i</code> to correctly represent the position in the flipped version.</p><h3 id="Standard-Solution-1"><a href="#Standard-Solution-1" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">L, i, j, major=<span class="literal">True</span></span>):</span><br><span class="line"> i1 = i = i - <span class="number">1</span></span><br><span class="line"> j1 = j = j - <span class="number">1</span></span><br><span class="line"> the_sum = L[i1][j1]</span><br><span class="line"> <span class="keyword">if</span> major:</span><br><span class="line"> <span class="keyword">while</span> (i1 := i1 - <span class="number">1</span>) >= <span class="number">0</span> <span class="keyword">and</span> (j1 := j1 - <span class="number">1</span>) >= <span class="number">0</span>:</span><br><span class="line"> the_sum += L[i1][j1]</span><br><span class="line"> i1, j1 = i, j</span><br><span class="line"> <span class="keyword">while</span> (i1 := i1 + <span class="number">1</span>) < <span class="built_in">len</span>(L) <span class="keyword">and</span> (j1 := j1 + <span class="number">1</span>) < <span class="built_in">len</span>(L):</span><br><span class="line"> the_sum += L[i1][j1]</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> <span class="keyword">while</span> (i1 := i1 - <span class="number">1</span>) >= <span class="number">0</span> <span class="keyword">and</span> (j1 := j1 + <span class="number">1</span>) < <span class="built_in">len</span>(L):</span><br><span class="line"> the_sum += L[i1][j1]</span><br><span class="line"> i1, j1 = i, j</span><br><span class="line"> <span class="keyword">while</span> (i1 := i1 + <span class="number">1</span>) < <span class="built_in">len</span>(L) <span class="keyword">and</span> (j1 := j1 - <span class="number">1</span>) >= <span class="number">0</span>:</span><br><span class="line"> the_sum += L[i1][j1]</span><br><span class="line"> <span class="keyword">return</span> the_sum</span><br></pre></td></tr></table></figure><h3 id="Explanation-2"><a href="#Explanation-2" class="headerlink" title="Explanation"></a>Explanation</h3><p>The standard solution uses a while loop to iterate through the elements of the matrix based on the given indices <code>i</code> and <code>j</code>. It calculates the sum of the diagonal elements by moving in the specified direction (major or minor diagonal) and updating the sum accordingly.</p><h1 id="Exercise-3"><a href="#Exercise-3" class="headerlink" title="Exercise 3"></a>Exercise 3</h1><h3 id="Problem-description-2"><a href="#Problem-description-2" class="headerlink" title="Problem description"></a>Problem description</h3><p>This exercise involves swapping elements in a square matrix with an even side length such that each element in a specified half (‘top’, ‘bottom’, ‘left’, or ‘right’) is at least equal to its diagonally opposite element.</p><p>If the half is ‘top’ or ‘left’, the element in that half should be at least equal to the diagonally opposite one, otherwise they should be swapped. Conversely, if the half is ‘bottom’ or ‘right’, the element in the other half should be swapped if it is greater.</p><h3 id="Standard-Solution-2"><a href="#Standard-Solution-2" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><p>The solution is implemented by creating a copy of the matrix and then iterating over the relevant half to determine if swapping is necessary based on the given criteria.</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Assume that the argument L is a list of lists of integers</span></span><br><span class="line"><span class="comment"># that displays as a square with an even side length</span></span><br><span class="line"><span class="comment"># and the argument half is one of</span></span><br><span class="line"><span class="comment"># 'top', 'bottom', 'left' or 'right'.</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Possibly swaps elements that are diagonally opposite</span></span><br><span class="line"><span class="comment"># so that the element in the "half" part of the square is</span></span><br><span class="line"><span class="comment"># at least equal to the other element.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">L, half=<span class="string">'top'</span></span>):</span><br><span class="line"> <span class="comment"># Create a copy of the original list to avoid modifying it directly</span></span><br><span class="line"> L1 = [<span class="built_in">list</span>(row) <span class="keyword">for</span> row <span class="keyword">in</span> L]</span><br><span class="line"> n = <span class="built_in">len</span>(L)</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Define ranges based on the specified half</span></span><br><span class="line"> ranges = {</span><br><span class="line"> <span class="string">'top'</span>: (<span class="built_in">range</span>(n // <span class="number">2</span>), <span class="built_in">range</span>(n)),</span><br><span class="line"> <span class="string">'bottom'</span>: (<span class="built_in">range</span>(n // <span class="number">2</span>, n), <span class="built_in">range</span>(n)),</span><br><span class="line"> <span class="string">'left'</span>: (<span class="built_in">range</span>(n), <span class="built_in">range</span>(n // <span class="number">2</span>)),</span><br><span class="line"> <span class="string">'right'</span>: (<span class="built_in">range</span>(n), <span class="built_in">range</span>(n // <span class="number">2</span>, n))</span><br><span class="line"> }</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Iterate through the specified half and possibly swap diagonally opposite elements</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> ranges[half][<span class="number">0</span>]:</span><br><span class="line"> <span class="keyword">for</span> j <span class="keyword">in</span> ranges[half][<span class="number">1</span>]:</span><br><span class="line"> <span class="keyword">if</span> L[i][j] < L[-i - <span class="number">1</span>][-j - <span class="number">1</span>]:</span><br><span class="line"> L1[i][j], L1[-i - <span class="number">1</span>][-j - <span class="number">1</span>] = L1[-i - <span class="number">1</span>][-j - <span class="number">1</span>], L1[i][j]</span><br><span class="line"> </span><br><span class="line"> <span class="keyword">return</span> L1</span><br></pre></td></tr></table></figure><h3 id="Explanation-3"><a href="#Explanation-3" class="headerlink" title="Explanation"></a>Explanation</h3><p>The approach in my solution uses a dictionary to define the ranges for each half of the matrix. By iterating over these ranges, it ensures that only the elements in the specified half are considered. If the element in the specified half is smaller than its diagonally opposite counterpart, they are swapped.</p><p>The ranges dictionary defines which rows and columns are to be iterated based on the specified half:</p><ul><li><code>'top'</code> considers the top half of the matrix (rows from <code>0</code> to <code>n//2</code>)</li><li><code>'bottom'</code> considers the bottom half of the matrix (rows from <code>n//2</code> to <code>n</code>)</li><li><code>'left'</code> considers the left half of the matrix (columns from <code>0</code> to <code>n//2</code>)</li><li><code>'right'</code> considers the right half of the matrix (columns from <code>n//2</code> to <code>n</code>)</li></ul><p>The values are swapped only if they do not meet the condition defined for the given half.</p><h1 id="Exercise-4"><a href="#Exercise-4" class="headerlink" title="Exercise 4"></a>Exercise 4</h1><h3 id="Problem-description-3"><a href="#Problem-description-3" class="headerlink" title="Problem description"></a>Problem description</h3><p>This exercise involves creating a visual pattern on an <code>n x n</code> grid using two different characters to represent black and white cells. The argument <code>n</code> is an integer at least equal to 1, and the argument <code>black_center</code> is either <code>True</code> or <code>False</code>, which influences the color of the center of the grid. The function should use <code>np.full()</code> to create the grid and modify it using simple loops without nested loops.</p><p>The function prints the grid instead of returning it.</p><h3 id="My-Solution-2"><a href="#My-Solution-2" class="headerlink" title="My Solution"></a>My Solution</h3><p>The solution starts by creating an <code>n x n</code> grid initialized entirely to either black or white, depending on whether the center should be black or not. The function then iteratively adjusts concentric squares within the grid, switching the colors as needed.</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">black</span>(<span class="params">i, black_centre</span>):</span><br><span class="line"> <span class="keyword">return</span> (i % <span class="number">4</span> <span class="keyword">in</span> {<span class="number">1</span>, <span class="number">2</span>}) ^ (<span class="keyword">not</span> black_centre)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">n, black_centre=<span class="literal">True</span></span>):</span><br><span class="line"> <span class="comment"># Create the initial grid based on the color of the center</span></span><br><span class="line"> grid = np.full((n, n), <span class="string">'⬛'</span>) <span class="keyword">if</span> black(n, black_centre)\</span><br><span class="line"> <span class="keyword">else</span> np.full((n, n), <span class="string">'⬜'</span>)</span><br><span class="line"> <span class="comment"># Adjust concentric squares within the grid</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, n // <span class="number">2</span> + <span class="number">1</span>):</span><br><span class="line"> grid[i : n - i, i : n - i] = <span class="string">'⬛'</span> <span class="keyword">if</span> black(n - <span class="number">2</span> * i, black_centre)\</span><br><span class="line"> <span class="keyword">else</span> <span class="string">'⬜'</span></span><br><span class="line"> <span class="comment"># Print the grid row by row</span></span><br><span class="line"> <span class="keyword">for</span> row <span class="keyword">in</span> grid:</span><br><span class="line"> <span class="built_in">print</span>(*row, sep=<span class="string">''</span>)</span><br></pre></td></tr></table></figure><h3 id="Explanation-4"><a href="#Explanation-4" class="headerlink" title="Explanation"></a>Explanation</h3><ul><li>The function <code>black(i, black_centre)</code> determines the color of the concentric square based on the current size <code>i</code> and whether the center should be black (<code>black_centre</code> argument).</li><li>The <code>np.full()</code> function is used to create the grid, either filled with black (‘⬛’) or white (‘⬜’), depending on the value of <code>black(n, black_centre)</code>, which determines the color of the center.</li><li>The <code>for</code> loop iterates through half of the matrix (<code>n // 2</code>), adjusting each concentric square layer by layer.<ul><li>The slicing operation <code>grid[i : n - i, i : n - i]</code> selects the relevant inner square and fills it with either black or white, alternating colors as determined by <code>black(n - 2 * i, black_centre)</code>.</li></ul></li><li>Finally, the grid is printed row by row, with each character printed consecutively for easy visualization.</li></ul><h3 id="Standard-Solution-3"><a href="#Standard-Solution-3" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">black</span>(<span class="params">i, black_centre</span>):</span><br><span class="line"> <span class="keyword">return</span> (i % <span class="number">4</span> <span class="keyword">in</span> {<span class="number">1</span>, <span class="number">2</span>}) ^ (<span class="keyword">not</span> black_centre)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">n, black_centre=<span class="literal">True</span></span>):</span><br><span class="line"> <span class="comment"># Create the grid, starting with the initial color based on the center</span></span><br><span class="line"> grid = np.full((n, n), <span class="string">'⬛'</span> <span class="keyword">if</span> black(n, black_centre) <span class="keyword">else</span> <span class="string">'⬜'</span>)</span><br><span class="line"> <span class="comment"># Iterate to adjust each concentric layer</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, n // <span class="number">2</span> + <span class="number">1</span>):</span><br><span class="line"> color = <span class="string">'⬛'</span> <span class="keyword">if</span> black(n - <span class="number">2</span> * i, black_centre) <span class="keyword">else</span> <span class="string">'⬜'</span></span><br><span class="line"> grid[i:n-i, i:n-i] = color</span><br><span class="line"> <span class="comment"># Print the grid</span></span><br><span class="line"> <span class="keyword">for</span> row <span class="keyword">in</span> grid:</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">''</span>.join(row))</span><br></pre></td></tr></table></figure><h3 id="Explanation-5"><a href="#Explanation-5" class="headerlink" title="Explanation"></a>Explanation</h3><p>The standard solution follows a similar approach to my solution but uses slightly different syntax to achieve the same result:</p><ul><li>The grid is created using <code>np.full()</code>, just like in my solution.</li><li>The loop iterates through each concentric layer, updating the color accordingly. The variable <code>color</code> is used to determine what color each inner square should be, making the assignment more readable.</li><li>The grid is printed in a slightly different way by joining the row’s elements into a single string (<code>print(''.join(row))</code>). This makes the output cleaner by removing the spaces between characters, which is purely aesthetic.</li></ul><p>The primary differences between my solution and the standard solution are the use of inline expressions for color selection and minor differences in how the final output is formatted when printed.</p><h1 id="Exercise-5"><a href="#Exercise-5" class="headerlink" title="Exercise 5"></a>Exercise 5</h1><h3 id="Problem-description-4"><a href="#Problem-description-4" class="headerlink" title="Problem description"></a>Problem description</h3><p>The exercise is to compute the sum of elements in a given row and column and display a colored square at their intersection based on the sign of the sum:</p><ul><li>A blue square (‘🟦’) if the sum is <code>0</code>.</li><li>A green square (‘🟩’) if the sum is strictly positive.</li><li>A red square (‘🟥’) if the sum is strictly negative.</li></ul><p>For example, given a list of lists representing the matrix:</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">. . 2 . .</span><br><span class="line">2 0 -3 7 -4</span><br><span class="line">. . -4 . .</span><br></pre></td></tr></table></figure><p>The function should compute the sum for each row and column, and update the intersection elements accordingly.</p><p>The function should use <code>np.sum()</code> and <code>np.sign()</code> to simplify calculations, and should use at most loops within loops, avoiding deeper nesting.</p><p>The output is printed, not returned.</p><h3 id="My-Solution-3"><a href="#My-Solution-3" class="headerlink" title="My Solution"></a>My Solution</h3><p>The solution uses NumPy to calculate the sum of each row and column. The function then iterates through the given list and determines the sign of the sum at each intersection, displaying the appropriate color.</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">L</span>):</span><br><span class="line"> <span class="comment"># Convert L to a numpy array for easier manipulation</span></span><br><span class="line"> L = np.array(L)</span><br><span class="line"> n_rows, n_cols = L.shape</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Calculate row and column sums</span></span><br><span class="line"> row_sums = np.<span class="built_in">sum</span>(L, axis=<span class="number">1</span>)</span><br><span class="line"> col_sums = np.<span class="built_in">sum</span>(L, axis=<span class="number">0</span>)</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Iterate through the list and determine the color for each intersection</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n_rows):</span><br><span class="line"> row = []</span><br><span class="line"> <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(n_cols):</span><br><span class="line"> intersection_sum = row_sums[i] + col_sums[j] - L[i][j] <span class="comment"># Avoid double counting L[i][j]</span></span><br><span class="line"> <span class="keyword">if</span> intersection_sum == <span class="number">0</span>:</span><br><span class="line"> row.append(<span class="string">'🟦'</span>) <span class="comment"># Blue square</span></span><br><span class="line"> <span class="keyword">elif</span> intersection_sum > <span class="number">0</span>:</span><br><span class="line"> row.append(<span class="string">'🟩'</span>) <span class="comment"># Green square</span></span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> row.append(<span class="string">'🟥'</span>) <span class="comment"># Red square</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">''</span>.join(row))</span><br><span class="line"></span><br><span class="line"><span class="comment"># Test with the provided statements</span></span><br><span class="line">statements = <span class="string">'from exercise_6_5 import f5; '</span>\</span><br><span class="line"> <span class="string">'f5([[4, -6, -5], [6, -7, 6]])'</span></span><br><span class="line"></span><br><span class="line">%%run_and_test python3 -c <span class="string">"$statements"</span></span><br><span class="line"></span><br><span class="line"><span class="string">'🟥🟥🟥\n'</span></span><br><span class="line"><span class="string">'🟩🟥🟦\n'</span></span><br></pre></td></tr></table></figure><h3 id="Explanation-6"><a href="#Explanation-6" class="headerlink" title="Explanation"></a>Explanation</h3><ul><li><strong>NumPy Conversion</strong>: The list <code>L</code> is converted to a NumPy array to take advantage of the efficient <code>np.sum()</code> function for computing sums.</li><li><strong>Row and Column Sums</strong>: The sums for rows and columns are computed separately using <code>np.sum()</code> with the appropriate <code>axis</code> argument.</li><li><strong>Iteration for Colors</strong>: The function then iterates over each element in the matrix to determine the color of the intersection based on the calculated row and column sums. The color is chosen as follows:<ul><li><code>'🟦'</code> (blue) for a sum of <code>0</code>.</li><li><code>'🟩'</code> (green) for a strictly positive sum.</li><li><code>'🟥'</code> (red) for a strictly negative sum.</li></ul></li><li><strong>Output</strong>: Finally, the grid is printed row by row.</li></ul><h3 id="Standard-Solution-4"><a href="#Standard-Solution-4" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">L</span>):</span><br><span class="line"> L1 = np.array(L)</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(L1.shape[<span class="number">0</span>]):</span><br><span class="line"> <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(L1.shape[<span class="number">1</span>]):</span><br><span class="line"> L[i][j] = { <span class="number">0</span>: <span class="string">'🟦'</span>,</span><br><span class="line"> <span class="number">1</span>: <span class="string">'🟩'</span>,</span><br><span class="line"> -<span class="number">1</span>: <span class="string">'🟥'</span></span><br><span class="line"> }[np.sign(np.<span class="built_in">sum</span>(L1[i, :])</span><br><span class="line"> + np.<span class="built_in">sum</span>(L1[: , j])</span><br><span class="line"> - L1[i, j]</span><br><span class="line"> )</span><br><span class="line"> ]</span><br><span class="line"> <span class="keyword">for</span> row <span class="keyword">in</span> L:</span><br><span class="line"> <span class="built_in">print</span>(*row, sep=<span class="string">''</span>)</span><br></pre></td></tr></table></figure><h3 id="Explanation-7"><a href="#Explanation-7" class="headerlink" title="Explanation"></a>Explanation</h3><p>The standard solution follows a similar approach to my solution but uses a dictionary to map the sign of the sum to the corresponding color. The <code>np.sign()</code> function is used to determine the sign of the sum, and the dictionary is used to select the appropriate color based on the sign.</p><h1 id="Exercise-6"><a href="#Exercise-6" class="headerlink" title="Exercise 6"></a>Exercise 6</h1><h3 id="Problem-description-5"><a href="#Problem-description-5" class="headerlink" title="Problem description"></a>Problem description</h3><p>This exercise is similar to Exercise 5, where we compute the sum of elements in a given row and column and display a colored square at their intersection based on the sign of the sum:</p><ul><li>A blue square (‘🟦’) if the sum is <code>0</code>.</li><li>A green square (‘🟩’) if the sum is strictly positive.</li><li>A red square (‘🟥’) if the sum is strictly negative.</li></ul><p>However, the main differences are:</p><ul><li><strong>Input Structure</strong>: The list <code>L</code> must be a <strong>square matrix</strong> (i.e., the number of rows equals the number of columns).</li><li><strong>Optimization Requirement</strong>: The solution for <code>f6</code> must avoid manual loops for computation (except for output). Instead, the solution must use <strong>vectorized operations</strong> in NumPy to enhance computational efficiency.</li><li><strong>Advanced NumPy Usage</strong>: The exercise explicitly suggests using advanced NumPy functions such as <code>np.vectorize()</code>, <code>np.newaxis</code>, and broadcasting.</li></ul><p>The output is printed, not returned.</p><h3 id="My-Solution-4"><a href="#My-Solution-4" class="headerlink" title="My Solution"></a>My Solution</h3><p>The solution for <code>f6</code> uses advanced NumPy techniques to fully vectorize the computations without using explicit loops (except for printing). It creates the required colored grid by computing the sum for each row and column and then using a vectorized mapping to determine the color.</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">L</span>):</span><br><span class="line"> L1 = np.array(L)</span><br><span class="line"> <span class="comment"># Vectorize the color selection based on the sum of row and column</span></span><br><span class="line"> <span class="keyword">for</span> row <span class="keyword">in</span> np.vectorize(<span class="keyword">lambda</span> e: { <span class="number">0</span>: <span class="string">'🟦'</span>,</span><br><span class="line"> <span class="number">1</span>: <span class="string">'🟩'</span>,</span><br><span class="line"> -<span class="number">1</span>: <span class="string">'🟥'</span></span><br><span class="line"> }[e]</span><br><span class="line"> )(np.sign(np.<span class="built_in">sum</span>(L1, axis=<span class="number">1</span>)[:, np.newaxis]</span><br><span class="line"> + np.<span class="built_in">sum</span>(L1.T, axis=<span class="number">1</span>)</span><br><span class="line"> - L1</span><br><span class="line"> )</span><br><span class="line"> ):</span><br><span class="line"> <span class="built_in">print</span>(*row, sep=<span class="string">''</span>)</span><br></pre></td></tr></table></figure><h3 id="Explanation-8"><a href="#Explanation-8" class="headerlink" title="Explanation"></a>Explanation</h3><ul><li><strong>Vectorization</strong>: The solution uses <code>np.vectorize()</code> to apply a function element-wise over an array, effectively mapping each sum to a specific color.</li><li><strong>Avoiding Loops</strong>: Instead of iterating through each element manually, the solution leverages NumPy’s vectorization to calculate row and column sums simultaneously.</li><li><strong>Broadcasting and <code>np.newaxis</code></strong>: The use of <code>[:, np.newaxis]</code> helps in broadcasting the row sums across the columns to facilitate efficient addition with the column sums. This allows the entire computation to be performed without explicit looping.</li><li><strong>Output</strong>: Finally, each row is printed with the appropriate color, similar to Exercise 5.</li></ul><h3 id="Key-Differences-from-Exercise-5"><a href="#Key-Differences-from-Exercise-5" class="headerlink" title="Key Differences from Exercise 5"></a>Key Differences from Exercise 5</h3><ol><li><strong>Input Structure</strong>: Exercise 5 allows any list of lists, whereas Exercise 6 requires a square matrix.</li><li><strong>Loop Usage</strong>: Exercise 5 uses explicit loops to calculate intersection sums, whereas Exercise 6 relies entirely on <strong>vectorized operations</strong> and avoids manual loops (except for printing).</li><li><strong>Efficiency</strong>: Exercise 6 is more computationally efficient, as it is designed to handle larger datasets using optimized NumPy operations, whereas Exercise 5 uses loops that can be slower for large matrices.</li></ol>]]></content>
<summary type="html"><h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="Problem-description"><a href="#Pr</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="9021" scheme="https://longsizhuo.github.io/tags/9021/"/>
</entry>
<entry>
<title>9021_TUT_5</title>
<link href="https://longsizhuo.github.io/post/231af838.html"/>
<id>https://longsizhuo.github.io/post/231af838.html</id>
<published>2024-10-07T13:00:00.000Z</published>
<updated>2024-10-22T05:06:02.499Z</updated>
<content type="html"><![CDATA[<h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="Problem-Description"><a href="#Problem-Description" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>We are given a list <code>L</code> and an integer <code>n</code>. The task is to repeatedly extend the list <code>L</code> a certain number of times (<code>n</code>) by multiplying each element of the list by an increasing factor. The factors start at <code>2</code> and increase by <code>1</code> for each iteration.</p><hr><p>In my solution, I used a while loop to iterate <code>n</code> times. In each iteration, I used a list comprehension to multiply each element of the list <code>L</code> by the current factor and then used the <code>extend()</code> method to add the new elements to the end of the list. Finally, I incremented the factor by <code>1</code> and decremented <code>n</code> by <code>1</code>.<br>Because of the description: <code>L'' == 3 * L', L' == 2 * L</code> …. </p><h3 id="My-Solution"><a href="#My-Solution" class="headerlink" title="My Solution"></a>My Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">L: <span class="built_in">list</span>, n: <span class="built_in">int</span></span>):</span><br><span class="line"> <span class="comment"># because of the des of L'' == 3 * L', L' == 2 * L ....</span></span><br><span class="line"> base = <span class="number">2</span></span><br><span class="line"> <span class="comment"># when n bigger than 0, base will always ++,</span></span><br><span class="line"> <span class="keyword">while</span> n:</span><br><span class="line"> <span class="comment"># I want use map() again, but list generator is more simple</span></span><br><span class="line"> <span class="comment"># extend() will add all the elements in the list to the end of the list</span></span><br><span class="line"> L.extend([i * base <span class="keyword">for</span> i <span class="keyword">in</span> L])</span><br><span class="line"> base += <span class="number">1</span></span><br><span class="line"> n -= <span class="number">1</span></span><br><span class="line"> <span class="keyword">return</span> L</span><br></pre></td></tr></table></figure><h3 id="Standard-Solution"><a href="#Standard-Solution" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">L, n</span>):</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">2</span>, n + <span class="number">2</span>):</span><br><span class="line"> L.extend([e * i <span class="keyword">for</span> e <span class="keyword">in</span> L])</span><br><span class="line"> <span class="keyword">return</span> L</span><br></pre></td></tr></table></figure><h3 id="Explanation"><a href="#Explanation" class="headerlink" title="Explanation"></a>Explanation</h3><ol><li><strong>My Solution</strong>: Uses a while loop where n is manually decremented after each iteration step by step since it can help me understand what we need. I keep track of the current base manually (base += 1).</li><li><strong>Standard Solution</strong>: Uses a for loop, which automatically increments i in each iteration. The range is explicitly set to go from 2 to n + 2, which avoids the need for manually handling the base.</li></ol><h1 id="Exercise-2"><a href="#Exercise-2" class="headerlink" title="Exercise 2"></a>Exercise 2</h1><h3 id="Problem-Description-1"><a href="#Problem-Description-1" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>We are given a list L and an integer n. The task is to extend the list L such that it becomes the first n members of an infinite list, which is defined as:</p><ul><li>L, followed by 2 * L, followed by 4 * L, followed by 8 * L, and so on.</li></ul><p>This means that:</p><ul><li>L is initially concatenated with 2 * L (all elements of L multiplied by 2). </li><li>Then, 4 * L (all elements of L multiplied by 4) is concatenated, followed by 8 * L, and so on, until the length of the list is at least n.</li></ul><p>The challenge is to achieve this without using any for or while loops.</p><hr><p>We can see the pattern here: <code>L, 2 * L, 4 * L, 8 * L, ...</code> until it reaches the length of n.</p><p>At first, I ignored the description that “without using any for or while loops.”</p><p>Here is my solution:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Assume that the argument L is a nonempty list of integers</span></span><br><span class="line"><span class="comment"># and the argument n is an integer at least equal to the</span></span><br><span class="line"><span class="comment"># length of L.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Given an integer x and a list of integers S,</span></span><br><span class="line"><span class="comment"># let x * S denote the list obtained from S</span></span><br><span class="line"><span class="comment"># by multiplying all its elements by x.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># L becomes the first n members of the infinite list</span></span><br><span class="line"><span class="comment"># defined as L concatenated with 2 * L concatenated</span></span><br><span class="line"><span class="comment"># with 4 * L concatenated with 8 * L...</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Use no for nor while statement.</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">L: <span class="built_in">list</span>, n: <span class="built_in">int</span></span>):</span><br><span class="line"> <span class="keyword">while</span> <span class="built_in">len</span>(L) < n:</span><br><span class="line"> L.extend([i * <span class="number">2</span> <span class="keyword">for</span> i <span class="keyword">in</span> L])</span><br><span class="line"> <span class="comment"># use the slice to cut the list to reach the length of n</span></span><br><span class="line"> <span class="keyword">return</span> L[:n]</span><br></pre></td></tr></table></figure><h3 id="Standard-Solution-1"><a href="#Standard-Solution-1" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">L, n</span>):</span><br><span class="line"> L.extend(e * <span class="number">2</span> <span class="keyword">for</span> e <span class="keyword">in</span> L <span class="keyword">if</span> <span class="built_in">len</span>(L) < n)</span><br><span class="line"> <span class="keyword">return</span> L</span><br></pre></td></tr></table></figure><h1 id="Exercise-3"><a href="#Exercise-3" class="headerlink" title="Exercise 3"></a>Exercise 3</h1><h3 id="Problem-Description-2"><a href="#Problem-Description-2" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>The goal of this problem is to process a list L, which contains nonempty lists of nonempty lists of integers, and return a pair of lists. Each of these lists will be filtered based on specific conditions related to the length of the sublists and the values inside them.</p><p>Here’s the task broken down:</p><ol><li><p>First List in the Pair:</p><ul><li>For each sublist <code>L'</code> of <code>L</code>, if the length of <code>L'</code> is at least <code>n</code>, then:</li><li>For each sublist <code>L''</code> of <code>L'</code>, if the sum of the elements of <code>L''</code> is strictly positive:</li><li>Collect all the strictly positive integers from <code>L''</code> and add them to the first list.</li></ul></li><li><p>Second List in the Pair:</p><ul><li>This is similar to the first list but slightly simpler:</li><li>For each sublist <code>L'</code> of <code>L</code>, if its length is at least n:</li><li>For each sublist <code>L''</code> of <code>L'</code>, if the sum of its members is strictly positive:</li><li>Directly collect all the strictly positive integers from <code>L''</code> and add them to the second list.</li></ul></li></ol><p>The task specifies that we must use <strong>list comprehensions</strong> only—no loops, functions, or other control structures.</p><h3 id="My-Solution-1"><a href="#My-Solution-1" class="headerlink" title="My Solution"></a>My Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">L, n</span>):</span><br><span class="line"> <span class="comment"># First list comprehension: we process L' for length and filter based on sum</span></span><br><span class="line"> first = [</span><br><span class="line"> [x <span class="keyword">for</span> L2 <span class="keyword">in</span> L1 <span class="keyword">if</span> <span class="built_in">sum</span>(L2) > <span class="number">0</span> <span class="keyword">for</span> x <span class="keyword">in</span> L2 <span class="keyword">if</span> x > <span class="number">0</span>]</span><br><span class="line"> <span class="keyword">for</span> L1 <span class="keyword">in</span> L <span class="keyword">if</span> <span class="built_in">len</span>(L1) >= n</span><br><span class="line"> ]</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Second list comprehension: similar filtering but simpler output structure</span></span><br><span class="line"> second = [</span><br><span class="line"> [x <span class="keyword">for</span> x <span class="keyword">in</span> L2 <span class="keyword">if</span> x > <span class="number">0</span>]</span><br><span class="line"> <span class="keyword">for</span> L1 <span class="keyword">in</span> L <span class="keyword">if</span> <span class="built_in">len</span>(L1) >= n <span class="keyword">for</span> L2 <span class="keyword">in</span> L1 <span class="keyword">if</span> <span class="built_in">sum</span>(L2) > <span class="number">0</span></span><br><span class="line"> ]</span><br><span class="line"> <span class="keyword">return</span> first, second</span><br></pre></td></tr></table></figure><h3 id="Explanation-1"><a href="#Explanation-1" class="headerlink" title="Explanation"></a>Explanation</h3><ol><li><p>First List (<code>first</code>):</p><ul><li>We first filter out the sublists <code>L1</code> whose length is at least <code>n</code> (<code>for L1 in L if len(L1) >= n</code>).</li><li>Inside this, for each valid <code>L1</code>, we process its members <code>L2</code> (which are sublists of integers). We check if the sum of elements of L2 is strictly positive (<code>if sum(L2) > 0</code>).</li><li>For each valid <code>L2</code>, we collect the strictly positive integers (<code>for x in L2 if x > 0</code>).</li><li>This gives us the first list of lists, where each list contains the positive integers from sublists of sublists whose sum is positive.</li></ul></li><li><p>Second List (<code>second</code>):</p><ul><li>Similar to the first list, but here we directly collect the strictly positive integers from the valid sublists <code>L2</code>, without additional nesting.</li><li>We again check that the sum of <code>L2</code> is strictly positive and that the length of <code>L1</code> is at least <code>n</code>.</li><li>The result is a more flattened structure than the first list.</li></ul></li><li><p>Key Concepts:</p><ul><li>Filtering: Both lists involve filtering based on the length of L1 and the sum of L2.</li><li>List Comprehensions: Used extensively to meet the problem’s requirement of not using explicit loops or other control structures.</li></ul></li></ol><h3 id="Standard-Solution-2"><a href="#Standard-Solution-2" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">L, n</span>):</span><br><span class="line"> <span class="keyword">return</span> ([[e <span class="keyword">for</span> L2 <span class="keyword">in</span> L1 <span class="keyword">if</span> <span class="built_in">sum</span>(L2) > <span class="number">0</span></span><br><span class="line"> <span class="keyword">for</span> e <span class="keyword">in</span> L2 <span class="keyword">if</span> e > <span class="number">0</span></span><br><span class="line"> ] <span class="keyword">for</span> L1 <span class="keyword">in</span> L <span class="keyword">if</span> <span class="built_in">len</span>(L1) >= n</span><br><span class="line"> ],</span><br><span class="line"> [[e <span class="keyword">for</span> e <span class="keyword">in</span> L2 <span class="keyword">if</span> e > <span class="number">0</span>]</span><br><span class="line"> <span class="keyword">for</span> L1 <span class="keyword">in</span> L <span class="keyword">if</span> <span class="built_in">len</span>(L1) >= n</span><br><span class="line"> <span class="keyword">for</span> L2 <span class="keyword">in</span> L1 <span class="keyword">if</span> <span class="built_in">sum</span>(L2) > <span class="number">0</span></span><br><span class="line"> ]</span><br><span class="line"> )</span><br></pre></td></tr></table></figure><h1 id="Exercise-4"><a href="#Exercise-4" class="headerlink" title="Exercise 4"></a>Exercise 4</h1><p>We are given a list <code>L</code> of integers, and the goal is to return a list of lists that consists of pairs of elements from the <strong>beginning</strong> and <strong>end</strong> of the list. Specifically:</p><ol><li>The number of pairs <code>n</code> at the beginning and the end should be as large as possible while maintaining symmetry.</li><li>If the length of <code>L</code> is odd, the remaining element in the middle (that cannot form a pair) should be included as a single list.</li><li>No <code>for</code> or <code>while</code> loops should be used in the implementation.</li></ol><h3 id="My-Solution-2"><a href="#My-Solution-2" class="headerlink" title="My Solution"></a>My Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">L: <span class="built_in">list</span>[<span class="built_in">int</span>]</span>) -> <span class="built_in">list</span>[<span class="built_in">list</span>[<span class="built_in">int</span>]]:</span><br><span class="line"> <span class="comment"># Calculate the number of pairs we can take from both the beginning and end.</span></span><br><span class="line"> n = <span class="built_in">len</span>(L) // <span class="number">2</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Take pairs from the beginning of the list. These are the first n // 2 pairs.</span></span><br><span class="line"> start_pairs = [L[i:i + <span class="number">2</span>] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, <span class="built_in">len</span>(L) // <span class="number">4</span> * <span class="number">2</span>, <span class="number">2</span>)]</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Take pairs from the end of the list. These are the last n // 2 pairs.</span></span><br><span class="line"> end_pairs = [L[i:i + <span class="number">2</span>] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(L) - (<span class="built_in">len</span>(L) // <span class="number">4</span> * <span class="number">2</span>), <span class="built_in">len</span>(L) - <span class="number">1</span>, <span class="number">2</span>)]</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Calculate the remaining part (middle element if the list length is odd).</span></span><br><span class="line"> remain_part = [L[<span class="built_in">len</span>(L) // <span class="number">4</span> * <span class="number">2</span> : <span class="built_in">len</span>(L) -(<span class="built_in">len</span>(L) // <span class="number">4</span> * <span class="number">2</span>)]] <span class="keyword">if</span> <span class="built_in">len</span>(L) % <span class="number">4</span> <span class="keyword">else</span> []</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Combine the start pairs, the remaining part (if any), and the end pairs.</span></span><br><span class="line"> <span class="keyword">return</span> start_pairs + remain_part + end_pairs <span class="keyword">if</span> remain_part <span class="keyword">else</span> start_pairs + end_pairs</span><br></pre></td></tr></table></figure><h3 id="Standard-Solution-3"><a href="#Standard-Solution-3" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">L</span>):</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">len</span>(L) % <span class="number">2</span>:</span><br><span class="line"> <span class="keyword">return</span> [L[i : i + <span class="number">2</span>] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, <span class="built_in">len</span>(L) // <span class="number">4</span> * <span class="number">2</span>, <span class="number">2</span>)] +\</span><br><span class="line"> [L[<span class="built_in">len</span>(L) // <span class="number">4</span> * <span class="number">2</span> : <span class="built_in">len</span>(L) -(<span class="built_in">len</span>(L) // <span class="number">4</span> * <span class="number">2</span>)]] +\</span><br><span class="line"> [L[i : i + <span class="number">2</span>] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(L) - (<span class="built_in">len</span>(L) // <span class="number">4</span> * <span class="number">2</span>), <span class="built_in">len</span>(L) - <span class="number">1</span>, <span class="number">2</span>)]</span><br><span class="line"> <span class="keyword">return</span> [L[i : i + <span class="number">2</span>] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, <span class="built_in">len</span>(L) - <span class="number">1</span>, <span class="number">2</span>)]</span><br></pre></td></tr></table></figure><h3 id="Explanation-2"><a href="#Explanation-2" class="headerlink" title="Explanation"></a>Explanation</h3><p>The reason of why we use <code>len(L) // 4 * 2</code> is that we want to get the number of pairs we can take from both the <strong>beginning</strong> and <strong>end</strong>.</p><p>We have a pair at the beginning and a pair at the end, so we need to divide the length of the list by <code>4</code> to get the number of pairs. We then multiply this by <code>2</code> to get the total number of elements in these pairs.</p><h1 id="Exercise-5"><a href="#Exercise-5" class="headerlink" title="Exercise 5"></a>Exercise 5</h1><p>Before E5, let’s do some exercises.</p><h3 id="Normal-dictionary"><a href="#Normal-dictionary" class="headerlink" title="Normal dictionary:"></a>Normal dictionary:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">d = {}</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="string">'a'</span>,<span class="string">'b'</span>,<span class="string">'c'</span>,<span class="string">'a'</span>,<span class="string">'b'</span>,<span class="string">'c'</span>):</span><br><span class="line"> <span class="keyword">if</span> i <span class="keyword">in</span> d:</span><br><span class="line"> d[i] += <span class="number">1</span></span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> <span class="comment"># need to initialize the value of the key</span></span><br><span class="line"> d[i] = <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(d)</span><br></pre></td></tr></table></figure><h3 id="defaultdict"><a href="#defaultdict" class="headerlink" title="defaultdict:"></a>defaultdict:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> defaultdict</span><br><span class="line"></span><br><span class="line">d = defaultdict(<span class="built_in">int</span>)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="string">'a'</span>,<span class="string">'b'</span>,<span class="string">'c'</span>,<span class="string">'a'</span>,<span class="string">'b'</span>,<span class="string">'c'</span>):</span><br><span class="line"> <span class="comment"># no need to initialize the value of the key</span></span><br><span class="line"> d[i] += <span class="number">1</span></span><br><span class="line"> </span><br><span class="line"><span class="built_in">print</span>(d)</span><br></pre></td></tr></table></figure><h3 id="Counter"><a href="#Counter" class="headerlink" title="Counter:"></a>Counter:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> Counter</span><br><span class="line"></span><br><span class="line"><span class="comment"># easy to count the number of each element</span></span><br><span class="line">d = Counter(<span class="string">'a'</span>,<span class="string">'b'</span>,<span class="string">'c'</span>,<span class="string">'a'</span>,<span class="string">'b'</span>,<span class="string">'c'</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(d)</span><br></pre></td></tr></table></figure><h3 id="Problem-Description-3"><a href="#Problem-Description-3" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>The task is to count the number of customers from different countries by reading a CSV file and then printing the count per country in alphabetical order.</p><p>The provided solutions use Python’s csv module to read the data and a dictionary (from the collections.defaultdict class) to keep track of the count of customers from each country.</p><h3 id="My-Solution-3"><a href="#My-Solution-3" class="headerlink" title="My Solution"></a>My Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> csv</span><br><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> defaultdict</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">filename= <span class="string">'customers-100.csv'</span></span>) -> <span class="literal">None</span>:</span><br><span class="line"> <span class="comment"># read the file</span></span><br><span class="line"> <span class="keyword">with</span> <span class="built_in">open</span>(filename, newline=<span class="string">''</span>) <span class="keyword">as</span> csvfile:</span><br><span class="line"> reader = csv.reader(csvfile)</span><br><span class="line"> <span class="built_in">next</span>(reader) <span class="comment"># skip the header</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># count the number of customers per country</span></span><br><span class="line"> count = defaultdict(<span class="built_in">int</span>)</span><br><span class="line"> <span class="keyword">for</span> row <span class="keyword">in</span> reader:</span><br><span class="line"> count[row[<span class="number">6</span>]] += <span class="number">1</span> <span class="comment"># country is in the 7th column</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Print the results sorted by country name</span></span><br><span class="line"> <span class="keyword">for</span> key, value <span class="keyword">in</span> <span class="built_in">sorted</span>(count.items()):</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f'<span class="subst">{value}</span> from <span class="subst">{key}</span>'</span>)</span><br></pre></td></tr></table></figure><h3 id="Standard-Solution-4"><a href="#Standard-Solution-4" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> csv</span><br><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> defaultdict</span><br><span class="line"></span><br><span class="line">countries = defaultdict(<span class="built_in">int</span>)</span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">'customers-100.csv'</span>) <span class="keyword">as</span> file:</span><br><span class="line"> _ = <span class="built_in">next</span>(file) <span class="comment"># skip the header</span></span><br><span class="line"> csv_file = csv.reader(file)</span><br><span class="line"> <span class="keyword">for</span> records <span class="keyword">in</span> csv_file:</span><br><span class="line"> countries[records[<span class="number">6</span>]] += <span class="number">1</span> <span class="comment"># country data is in the 7th column</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Print the results sorted by country name</span></span><br><span class="line"><span class="keyword">for</span> country <span class="keyword">in</span> <span class="built_in">sorted</span>(countries):</span><br><span class="line"> <span class="built_in">print</span>(countries[country], <span class="string">'from'</span>, country)</span><br></pre></td></tr></table></figure><h3 id="Additional-Solution"><a href="#Additional-Solution" class="headerlink" title="Additional Solution"></a>Additional Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> csv</span><br><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> Counter</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f5_counter</span>(<span class="params">filename=<span class="string">'customers-100.csv'</span></span>) -> <span class="literal">None</span>:</span><br><span class="line"> <span class="keyword">with</span> <span class="built_in">open</span>(filename, newline=<span class="string">''</span>) <span class="keyword">as</span> csvfile:</span><br><span class="line"> reader = csv.reader(csvfile)</span><br><span class="line"> <span class="built_in">next</span>(reader) <span class="comment"># skip the header</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Create a Counter from the country column (assumed to be the 7th column)</span></span><br><span class="line"> country_counter = Counter(row[<span class="number">6</span>] <span class="keyword">for</span> row <span class="keyword">in</span> reader)</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Print the results sorted by country name</span></span><br><span class="line"> <span class="keyword">for</span> key, value <span class="keyword">in</span> <span class="built_in">sorted</span>(country_counter.items()):</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f'<span class="subst">{value}</span> from <span class="subst">{key}</span>'</span>)</span><br><span class="line"></span><br><span class="line">f5_counter()</span><br></pre></td></tr></table></figure><h3 id="Additional-Additional-Solution-Data-Analysis-NOT-Mandatory"><a href="#Additional-Additional-Solution-Data-Analysis-NOT-Mandatory" class="headerlink" title="Additional Additional Solution (Data Analysis) (NOT Mandatory)"></a>Additional Additional Solution (Data Analysis) (NOT Mandatory)</h3><p><strong>Not Mandatory</strong>, but it’s a good way to learn how to use pandas to do data analysis.</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"></span><br><span class="line"><span class="comment"># read file by pandas</span></span><br><span class="line">df = pd.read_csv(<span class="string">"customers-100.csv"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># use pandas' count()</span></span><br><span class="line">country_counts = df[<span class="string">'Country'</span>].value_counts().sort_index()</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> country, count <span class="keyword">in</span> country_counts.items():</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f'<span class="subst">{count}</span> from <span class="subst">{country}</span>'</span>)</span><br></pre></td></tr></table></figure><h3 id="Explanation-3"><a href="#Explanation-3" class="headerlink" title="Explanation"></a>Explanation</h3><h4 id="Reading-the-CSV-file"><a href="#Reading-the-CSV-file" class="headerlink" title="Reading the CSV file:"></a>Reading the CSV file:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">df = pd.read_csv(filename)</span><br></pre></td></tr></table></figure><p>Using the <code>read_csv()</code> function, Pandas can directly load a CSV file into a <code>DataFrame</code> object, which is similar to a table structure. Each column becomes an attribute of the <code>DataFrame</code>, and the column names automatically become the labels for the <code>DataFrame</code>.</p><h4 id="Counting-the-number-of-customers-per-country"><a href="#Counting-the-number-of-customers-per-country" class="headerlink" title="Counting the number of customers per country:"></a>Counting the number of customers per country:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">df[<span class="string">'Country'</span>].value_counts()</span><br></pre></td></tr></table></figure><p><code>Pandas</code> provides the <code>value_counts()</code> method, which can directly count the frequency of each value in a column. Here, we call <code>value_counts()</code> on the <code>Country</code> column to get the number of customers from each country.</p><h1 id="Exercise-6"><a href="#Exercise-6" class="headerlink" title="Exercise 6"></a>Exercise 6</h1><h3 id="Problem-Description-4"><a href="#Problem-Description-4" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>The task is to create a directory structure where:</p><p><img src="../assets/img/2024-10-08.png" alt="2024-10-08.png"></p><ul><li>There is a top-level directory named <code>First_10_words_per_letter</code>.</li><li>Under this directory, there are two subdirectories:<ul><li><strong>Vowels</strong>: Containing files for letters <code>A</code>, <code>E</code>, <code>I</code>, <code>O</code>, <code>U</code>, <code>Y</code>.</li><li><strong>Consonants</strong>: Containing files for the rest of the letters in the alphabet (B, C, D, etc.).</li></ul></li><li>Each letter (A to Z) has its own file, and each file contains the first 10 words from a dictionary.txt file that start with that letter.</li><li>The directory structure and the files should be generated programmatically, without using any existing hierarchy.</li></ul><h3 id="My-Solution-Not-Perfect-it-relies-on-the-sort-of-dictionary-txt"><a href="#My-Solution-Not-Perfect-it-relies-on-the-sort-of-dictionary-txt" class="headerlink" title="My Solution(Not Perfect, it relies on the sort of dictionary.txt )"></a>My Solution(Not Perfect, it relies on the sort of dictionary.txt )</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">from</span> pathlib <span class="keyword">import</span> Path</span><br><span class="line"><span class="keyword">from</span> string <span class="keyword">import</span> ascii_uppercase</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">main</span>():</span><br><span class="line"> <span class="comment"># Create the top directory</span></span><br><span class="line"> top_dir = Path(<span class="string">'First_10_words_per_letter'</span>)</span><br><span class="line"> <span class="comment"># Create the subdirectories</span></span><br><span class="line"> vowels_dir = top_dir / <span class="string">'Vowels'</span></span><br><span class="line"> consonants_dir = top_dir / <span class="string">'Consonants'</span></span><br><span class="line"> os.makedirs(vowels_dir)</span><br><span class="line"> os.makedirs(consonants_dir)</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Create the files for each letter</span></span><br><span class="line"> <span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">'dictionary.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line"> <span class="keyword">for</span> letter <span class="keyword">in</span> ascii_uppercase:</span><br><span class="line"> <span class="comment"># Read the first 10 words starting with the letter</span></span><br><span class="line"> count = <span class="number">0</span></span><br><span class="line"> <span class="comment"># Write the words to the file</span></span><br><span class="line"> letter_dir = vowels_dir <span class="keyword">if</span> letter <span class="keyword">in</span> <span class="string">'AEIOUY'</span> <span class="keyword">else</span> consonants_dir</span><br><span class="line"> <span class="keyword">with</span> <span class="built_in">open</span>(letter_dir / <span class="string">f'<span class="subst">{letter}</span>.txt'</span>, <span class="string">'w'</span>) <span class="keyword">as</span> f2:</span><br><span class="line"> <span class="keyword">for</span> word <span class="keyword">in</span> f:</span><br><span class="line"> <span class="keyword">if</span> word[<span class="number">0</span>] == letter:</span><br><span class="line"> f2.write(word)</span><br><span class="line"> count += <span class="number">1</span></span><br><span class="line"> <span class="keyword">if</span> count >= <span class="number">10</span>:</span><br><span class="line"> <span class="keyword">break</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line"> main()</span><br></pre></td></tr></table></figure><h3 id="Explanation-4"><a href="#Explanation-4" class="headerlink" title="Explanation"></a>Explanation</h3><p>Explanation of My Solution:</p><ol><li><p>Creating Directories:</p><ul><li>I use <code>os.makedirs()</code> to create the top directory (<code>First_10_words_per_letter</code>) and its subdirectories (<code>Vowels</code> and <code>Consonants</code>).</li></ul></li><li><p>Reading the Dictionary File:</p><ul><li>The program reads from dictionary.txt and processes each letter in the alphabet (ascii_uppercase).</li><li>For each letter, I decide whether to place the corresponding file in the Vowels or Consonants subdirectory based on whether the letter is a vowel or consonant.</li></ul></li><li><p>Writing the Words:</p><ul><li>The program writes the first 10 words starting with the given letter into the corresponding .txt file.</li></ul></li><li><p>Potential Issue:</p><ul><li>here is some limitations of this. Say that processing the dictionary on the fly would not be an option if the words in the file were not lexicographically ordered?</li></ul></li></ol><h3 id="Standard-Solution-5"><a href="#Standard-Solution-5" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">from</span> pathlib <span class="keyword">import</span> Path</span><br><span class="line"><span class="keyword">from</span> string <span class="keyword">import</span> ascii_uppercase</span><br><span class="line"></span><br><span class="line">top_dir = Path(<span class="string">'First_10_words_per_letter'</span>)</span><br><span class="line">os.mkdir(top_dir)</span><br><span class="line">vowels_dir = top_dir / <span class="string">'Vowels'</span></span><br><span class="line">consonants_dir = top_dir / <span class="string">'Consonants'</span></span><br><span class="line">os.mkdir(vowels_dir)</span><br><span class="line">os.mkdir(consonants_dir)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">'dictionary.txt'</span>) <span class="keyword">as</span> dictionary:</span><br><span class="line"> <span class="keyword">for</span> letter <span class="keyword">in</span> ascii_uppercase:</span><br><span class="line"> letter_dir = vowels_dir <span class="keyword">if</span> letter <span class="keyword">in</span> <span class="string">'AEIOUY'</span> <span class="keyword">else</span> consonants_dir</span><br><span class="line"> count = <span class="number">0</span></span><br><span class="line"> <span class="keyword">with</span> <span class="built_in">open</span>(letter_dir / <span class="string">f'<span class="subst">{letter}</span>.txt'</span>, <span class="string">'w'</span>) <span class="keyword">as</span> filename:</span><br><span class="line"> <span class="keyword">for</span> word <span class="keyword">in</span> dictionary:</span><br><span class="line"> <span class="keyword">if</span> word[<span class="number">0</span>] != letter:</span><br><span class="line"> <span class="keyword">continue</span></span><br><span class="line"> <span class="keyword">if</span> count >= <span class="number">10</span>:</span><br><span class="line"> <span class="keyword">break</span></span><br><span class="line"> <span class="built_in">print</span>(word, file=filename, end=<span class="string">''</span>)</span><br><span class="line"> count += <span class="number">1</span></span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="Problem-Description"><a href="#Pr</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="9021" scheme="https://longsizhuo.github.io/tags/9021/"/>
<category term="TUT" scheme="https://longsizhuo.github.io/tags/TUT/"/>
</entry>
<entry>
<title>Horse Racing-Inter-Uni Programming Contest</title>
<link href="https://longsizhuo.github.io/post/7ab03a1b.html"/>
<id>https://longsizhuo.github.io/post/7ab03a1b.html</id>
<published>2024-10-03T08:57:12.475Z</published>
<updated>2024-10-03T08:57:12.475Z</updated>
<content type="html"><![CDATA[<h1 id="Description"><a href="#Description" class="headerlink" title="Description:"></a>Description:</h1><p><a href="https://interunia.unswcpmsoc.com/task/Horse%20Racing/">https://interunia.unswcpmsoc.com/task/Horse%20Racing/</a></p><h1 id="Thinking"><a href="#Thinking" class="headerlink" title="Thinking:"></a>Thinking:</h1><h3 id="Preprocessing-Horse-Information"><a href="#Preprocessing-Horse-Information" class="headerlink" title="Preprocessing Horse Information:"></a>Preprocessing Horse Information:</h3><p>Combine horse information into a list of tuples, <code>horses</code>, where each tuple contains the horse index, starting position, and velocity.<br>Sort the horses by starting position in descending order. If two horses have the same starting position, sort them by velocity in descending order. This is because the horse with the highest starting position leads initially.</p><h3 id="Constructing-the-Leading-Horse-Timeline"><a href="#Constructing-the-Leading-Horse-Timeline" class="headerlink" title="Constructing the Leading Horse Timeline:"></a>Constructing the Leading Horse Timeline:</h3><ul><li>Use a stack <code>stack</code> to maintain the horses that could become the leader.</li><li>For each horse, check if it has the potential to overtake the current leading horse.<ul><li>If the current horse’s speed is less than or equal to the horse at the top of the stack, it can never overtake and is discarded.</li><li>If the current horse’s speed is greater than the top horse’s, calculate when it will overtake the current leader.</li><li>If the calculated overtaking time is invalid (e.g., earlier than the previous overtaking time), adjust the stack by removing horses that can no longer lead.</li></ul></li></ul><h3 id="Handling-Queries"><a href="#Handling-Queries" class="headerlink" title="Handling Queries:"></a>Handling Queries:</h3><p>Use binary search to handle each query time <code>t</code> in the <code>times</code> list to find the corresponding leading horse.<br><code>bisect.bisect_right(times, t) - 1</code> finds the first time point greater than <code>t</code>, then subtract one to get the corresponding horse index.</p><p><strong>Timeline Construction</strong>: We build a timeline that records the time points when the leading horse changes and the horse that leads during that period.</p><p><strong>Binary Search for Queries</strong>: Since the timeline is sorted chronologically, we can efficiently find the leading horse for each query time using binary search.</p><h1 id="Codes"><a href="#Codes" class="headerlink" title="Codes:"></a>Codes:</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">n, q = <span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split())</span><br><span class="line">s_list = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split()))</span><br><span class="line">v_list = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split()))</span><br><span class="line">t_list = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split()))</span><br><span class="line"></span><br><span class="line">horses = <span class="built_in">list</span>(<span class="built_in">zip</span>(<span class="built_in">range</span>(n), s_list, v_list))</span><br><span class="line"><span class="comment"># Sort horses by decreasing s_i</span></span><br><span class="line">horses.sort(key=<span class="keyword">lambda</span> x: (-x[<span class="number">1</span>], -x[<span class="number">2</span>])) <span class="comment"># (-s_i, -v_i)</span></span><br><span class="line"></span><br><span class="line">stack = []</span><br><span class="line"><span class="comment"># 存储每次马匹变化的时间点</span></span><br><span class="line">times = []</span><br><span class="line"><span class="comment"># 存储每次马匹变化的编号</span></span><br><span class="line">horse_indices = []</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> idx, s_i, v_i <span class="keyword">in</span> horses:</span><br><span class="line"> discard = <span class="literal">False</span></span><br><span class="line"> <span class="comment"># 检查是否可以领先</span></span><br><span class="line"> <span class="keyword">while</span> stack:</span><br><span class="line"> <span class="comment"># 看看顶部</span></span><br><span class="line"> jdx, s_j, v_j = stack[-<span class="number">1</span>]</span><br><span class="line"> <span class="keyword">if</span> v_i <= v_j:</span><br><span class="line"> <span class="comment"># 如果它的速度小于或等于当前领导者的速度,它永远无法超越并被丢弃。</span></span><br><span class="line"> discard = <span class="literal">True</span></span><br><span class="line"> <span class="keyword">break</span></span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> <span class="comment"># Compute t_int</span></span><br><span class="line"> t_prev = times[-<span class="number">1</span>] <span class="keyword">if</span> times <span class="keyword">else</span> <span class="number">0.0</span></span><br><span class="line"> <span class="comment"># 可能超过的时间</span></span><br><span class="line"> t_int = (s_j - s_i) / (v_i - v_j)</span><br><span class="line"> <span class="keyword">if</span> t_int <= t_prev:</span><br><span class="line"> stack.pop()</span><br><span class="line"> times.pop()</span><br><span class="line"> horse_indices.pop()</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> <span class="keyword">break</span></span><br><span class="line"> <span class="keyword">if</span> <span class="keyword">not</span> discard:</span><br><span class="line"> <span class="keyword">if</span> stack:</span><br><span class="line"> t_int = (s_j - s_i) / (v_i - v_j)</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> t_int = <span class="number">0.0</span></span><br><span class="line"> stack.append((idx, s_i, v_i))</span><br><span class="line"> times.append(t_int)</span><br><span class="line"> horse_indices.append(idx)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> bisect</span><br><span class="line"></span><br><span class="line">result = []</span><br><span class="line"><span class="keyword">for</span> t <span class="keyword">in</span> t_list:</span><br><span class="line"> idx = bisect.bisect_right(times, t) -<span class="number">1</span></span><br><span class="line"> idx = <span class="built_in">max</span>(<span class="number">0</span>, idx)</span><br><span class="line"> result.append(horse_indices[idx]+<span class="number">1</span>) <span class="comment"># +1 to convert to 1-based indexing</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">' '</span>.join(<span class="built_in">map</span>(<span class="built_in">str</span>, result)))</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="Description"><a href="#Description" class="headerlink" title="Description:"></a>Description:</h1><p><a href="https://interunia.unswc</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="Contest" scheme="https://longsizhuo.github.io/tags/Contest/"/>
</entry>
<entry>
<title>Counting Stars-Inter-Uni Programming Contest</title>
<link href="https://longsizhuo.github.io/post/a29b0a05.html"/>
<id>https://longsizhuo.github.io/post/a29b0a05.html</id>
<published>2024-10-03T08:57:12.474Z</published>
<updated>2024-10-03T08:57:12.474Z</updated>
<content type="html"><![CDATA[<h1 id="Description"><a href="#Description" class="headerlink" title="Description:"></a>Description:</h1><p><a href="https://interunia.unswcpmsoc.com/task/Counting%20Stars/">https://interunia.unswcpmsoc.com/task/Counting%20Stars/</a></p><h1 id="Thinking"><a href="#Thinking" class="headerlink" title="Thinking:"></a>Thinking:</h1><ul><li>Given a set of star positions, we need to calculate the minimum number of stars required to explain these positions.</li><li>Meteors (i.e., moving stars) move from left to right, and from high to low (x coordinates increase, y coordinates decrease), without moving horizontally or vertically.</li><li>Each meteor may appear in multiple positions (because it moves), and the final cumulative image will show all the positions it has passed through.</li><li>The positions of fixed stars remain unchanged.</li></ul><p>Therefore, we need to maintain a list of the <strong>last y-coordinate of the current chain</strong>.</p><ol><li><strong>Sort the points</strong>: Sort them by increasing x coordinates.</li><li><strong>Initialization</strong>: Create an empty list <code>last_y</code> to store the last y-coordinate of each chain.</li><li><strong>Traverse the set of points</strong>:<ul><li>For each point (x, y):<ul><li>Use <code>bisect_right</code> to find the first position in <code>last_y</code> that is greater than the current y.</li><li>If the index is less than the length of <code>last_y</code>, it means there is an existing chain that can accommodate the current point, so we update the last y-coordinate of that chain to the current y.</li><li>If the index is equal to the length of <code>last_y</code>, it means no suitable chain is found, so we need to create a new chain and add the current y to <code>last_y</code>.</li></ul></li></ul></li></ol><h1 id="Code"><a href="#Code" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> bisect</span><br><span class="line"></span><br><span class="line">n = <span class="built_in">int</span>(<span class="built_in">input</span>())</span><br><span class="line">stars = []</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line"> x, y = <span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split())</span><br><span class="line"> stars.append((x, y))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 按 x 坐标递增排序</span></span><br><span class="line">stars.sort(key=<span class="keyword">lambda</span> x: (x[<span class="number">0</span>],))</span><br><span class="line"></span><br><span class="line">last_y = []</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> x, y <span class="keyword">in</span> stars:</span><br><span class="line"> idx = bisect.bisect_right(last_y, y)</span><br><span class="line"> <span class="keyword">if</span> idx < <span class="built_in">len</span>(last_y):</span><br><span class="line"> last_y[idx] = y <span class="comment"># 更新链的最后一个 y 坐标</span></span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> last_y.append(y) <span class="comment"># 创建新的链</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">len</span>(last_y))</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="Description"><a href="#Description" class="headerlink" title="Description:"></a>Description:</h1><p><a href="https://interunia.unswc</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="Contest" scheme="https://longsizhuo.github.io/tags/Contest/"/>
<category term="Binary Search" scheme="https://longsizhuo.github.io/tags/Binary-Search/"/>
</entry>
<entry>
<title>9021_TUT_3</title>
<link href="https://longsizhuo.github.io/post/671a7e4.html"/>
<id>https://longsizhuo.github.io/post/671a7e4.html</id>
<published>2024-10-03T08:57:12.473Z</published>
<updated>2024-10-03T08:57:12.473Z</updated>
<content type="html"><![CDATA[<h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="Problem-Description"><a href="#Problem-Description" class="headerlink" title="Problem Description:"></a>Problem Description:</h3><p>You are given two integers, <code>m</code> and <code>n</code>, where:</p><ul><li><code>m</code> represents the number of repeated units (patterns).</li><li><code>n</code> represents the number of elements (underscores) within each unit.</li></ul><p>The goal is to generate a string where:</p><ul><li>Each unit contains <code>n</code> underscores (_), separated by <code>|</code>.</li><li>These units are then concatenated together, separated by <code>*</code>.</li></ul><h3 id="My-Solution"><a href="#My-Solution" class="headerlink" title="My Solution:"></a>My Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">generate_struct</span>(<span class="params">n</span>):</span><br><span class="line"> <span class="keyword">return</span> <span class="string">'|'</span>.join(n * [<span class="string">'_'</span>])</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">m, n</span>):</span><br><span class="line"> <span class="keyword">return</span> <span class="string">' * '</span>.join(m * [generate_struct(n)])</span><br></pre></td></tr></table></figure><h4 id="My-Thought-Process"><a href="#My-Thought-Process" class="headerlink" title="My Thought Process:"></a>My Thought Process:</h4><p>I think of each unit as a separate structure. So, I decompose the problem by breaking down the smallest unit, which is the structure made of underscores joined by <code>|</code>.<br>After constructing each unit, I use <code>join()</code> to combine them together using <code>*</code>.</p><h4 id="Helper-Function-generate-struct-n"><a href="#Helper-Function-generate-struct-n" class="headerlink" title="Helper Function generate_struct(n):"></a>Helper Function generate_struct(n):</h4><p>This function generates the basic structure.<br>It creates a list of underscores (<code>_</code>) of length n and joins them with <code>|</code>.<br>Example: If <code>n = 2</code>, the result will be “<code>_|_</code>“.</p><h3 id="Standard-Solution"><a href="#Standard-Solution" class="headerlink" title="Standard Solution:"></a>Standard Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">m, n</span>):</span><br><span class="line"> <span class="keyword">return</span> <span class="string">' * '</span>.join(<span class="string">'|'</span>.join(<span class="string">'_'</span> <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(n)) <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(m))</span><br></pre></td></tr></table></figure><h3 id="Concise-Expression"><a href="#Concise-Expression" class="headerlink" title="Concise Expression:"></a>Concise Expression:</h3><p>The inner <code>join</code> creates a string of <code>n</code> underscores joined by <code>|</code> using a generator expression <code>('_' for _ in range(n))</code>.<br>The outer <code>join</code> repeats this process <code>m</code> times and concatenates the units using <code>*</code>.</p><p>In summary, my solution focuses on modularity by breaking down the problem into smaller parts (like creating a structural unit), whereas the standard solution compresses everything into one line using list comprehensions.</p><h1 id="Exercise-2"><a href="#Exercise-2" class="headerlink" title="Exercise 2"></a>Exercise 2</h1><h3 id="Problem-Description-1"><a href="#Problem-Description-1" class="headerlink" title="Problem Description:"></a>Problem Description:</h3><p>The goal is to generate a pattern based on the digits of a given number n. Specifically:</p><p>If a digit is odd, it should be represented by a black square (⬛).<br>If a digit is even, it should be represented by a white square (⬜).<br>The program takes a number n as input and prints a string of squares corresponding to the digits of n.</p><h3 id="My-Solution-1"><a href="#My-Solution-1" class="headerlink" title="My Solution:"></a>My Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">n</span>):</span><br><span class="line"> ans = <span class="string">''</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">str</span>(n):</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">int</span>(i) % <span class="number">2</span> == <span class="number">0</span>:</span><br><span class="line"> ans += <span class="string">'⬜'</span></span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> ans += <span class="string">'⬛'</span></span><br><span class="line"> <span class="built_in">print</span>(ans)</span><br></pre></td></tr></table></figure><h4 id="My-Thought-Process-1"><a href="#My-Thought-Process-1" class="headerlink" title="My Thought Process:"></a>My Thought Process:</h4><ol><li><p>Loop through each digit:<br>Convert the number n to a string to iterate over each digit individually.</p></li><li><p>Check if the digit is even or odd:<br>Convert each digit back to an integer and use the modulus operator (% 2) to check if the digit is even or odd.</p></li><li><p>Append the corresponding square:</p><ul><li>If the digit is even, append a white square (⬜) to the result string.</li><li>If the digit is odd, append a black square (⬛).</li></ul></li><li><p>Print the final string:<br>After processing all the digits, print the final string containing black and white squares.</p></li></ol><h3 id="Standard-Solution-1"><a href="#Standard-Solution-1" class="headerlink" title="Standard Solution:"></a>Standard Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">n</span>):</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">''</span>.join({<span class="number">0</span>: <span class="string">'\u2b1c'</span>, <span class="number">1</span>: <span class="string">'\u2b1b'</span>}[<span class="built_in">int</span>(d) % <span class="number">2</span>] <span class="keyword">for</span> d <span class="keyword">in</span> <span class="built_in">str</span>(n)))</span><br></pre></td></tr></table></figure><p>Dr.Martin’s solution is:</p><ol><li>More compact and Pythonic.</li><li>Uses a dictionary and list comprehension for brevity and efficiency.</li><li>The Unicode characters for the squares are referenced directly using their escape sequences (<code>\u2b1c</code> for white, <code>\u2b1b</code> for black).</li></ol><h1 id="Exercise-3"><a href="#Exercise-3" class="headerlink" title="Exercise 3"></a>Exercise 3</h1><h3 id="Problem-Description-2"><a href="#Problem-Description-2" class="headerlink" title="Problem Description:"></a>Problem Description:</h3><p>In this task, the number <code>n</code> is treated as a number expressed in different bases (ranging from 2 to 10), and we aim to convert it into its corresponding base 10 value for each of these bases, where the conversion is valid.</p><p>For n = 2143:</p><ul><li><code>2143</code> in base <code>5</code> is equivalent to <code>298</code> in base <code>10</code>.</li><li><code>2143</code> in base <code>6</code> is equivalent to <code>495</code> in base <code>10</code>.</li><li>And so on.</li></ul><p>The goal is to iterate over different base systems from 2 to 10, treat the input number <code>n</code> as if it is expressed in each base, and then convert it to base 10.</p><h3 id="My-Solution-2"><a href="#My-Solution-2" class="headerlink" title="My Solution:"></a>My Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">n: <span class="built_in">int</span></span>):</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">2</span>, <span class="number">11</span>):</span><br><span class="line"> <span class="keyword">try</span>:</span><br><span class="line"> <span class="comment"># Treat n as a number in base i and convert it to base 10</span></span><br><span class="line"> value = <span class="built_in">int</span>(<span class="built_in">str</span>(n), i)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f'<span class="subst">{n}</span> is <span class="subst">{value}</span> in base <span class="subst">{i}</span>'</span>)</span><br><span class="line"> <span class="keyword">except</span> ValueError:</span><br><span class="line"> <span class="keyword">pass</span></span><br></pre></td></tr></table></figure><h4 id="My-Thought-Process-2"><a href="#My-Thought-Process-2" class="headerlink" title="My Thought Process:"></a>My Thought Process:</h4><ol><li><p>Iterating over Bases (2 to 10):</p><ul><li>We loop through the base values i ranging from 2 to 10.</li></ul></li><li><p>Conversion Using <code>int()</code>:</p><ul><li>For each base <code>i</code>, we treat the number <code>n</code> as a number in that base. To do this, we first convert <code>n</code> to a string (<code>str(n)</code>) and then use <code>int()</code> to interpret it as a base <code>i</code> number.</li><li>If the digits of <code>n</code> are valid for base <code>i</code>, this conversion succeeds, and the result is the base 10 equivalent of <code>n</code>.</li><li>If the digits of n are not valid for base i (for example, if base 2 is used and n contains digits greater than 1), a ValueError is raised, and we skip the invalid base.</li></ul></li><li><p>Handling Errors with <code>try-except</code>:</p><ul><li>The <code>try-except</code> block ensures that invalid bases are skipped, allowing us to handle cases where the digits in <code>n</code> are not valid for a particular base.</li></ul></li></ol><h3 id="Standard-Solution-2"><a href="#Standard-Solution-2" class="headerlink" title="Standard Solution:"></a>Standard Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">n</span>):</span><br><span class="line"> n_as_string = <span class="built_in">str</span>(n)</span><br><span class="line"> min_base = <span class="built_in">max</span>(<span class="number">2</span>, <span class="built_in">max</span>({<span class="built_in">int</span>(d) <span class="keyword">for</span> d <span class="keyword">in</span> n_as_string}) + <span class="number">1</span>)</span><br><span class="line"> <span class="keyword">for</span> b <span class="keyword">in</span> <span class="built_in">range</span>(min_base, <span class="number">11</span>):</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f'<span class="subst">{n}</span> is <span class="subst">{<span class="built_in">int</span>(n_as_string, b)}</span> in base <span class="subst">{b}</span>'</span>)</span><br></pre></td></tr></table></figure><p>It skips the bases where the digits in n are not valid, and it uses a set comprehension to extract the unique digits from n_as_string. The maximum digit is then used to determine the minimum base to start iterating from.</p><h1 id="Exercise-4"><a href="#Exercise-4" class="headerlink" title="Exercise 4"></a>Exercise 4</h1><h3 id="Problem-Description-3"><a href="#Problem-Description-3" class="headerlink" title="Problem Description:"></a>Problem Description:</h3><p>The task is to create a function <code>f4(n, base)</code> that returns a dictionary D, where:</p><p>Keys are integers from <code>0</code> to <code>n</code>.<br>Values are tuples that represent the base <code>base</code> representation of each key, converted from base 10.</p><h3 id="My-Solution-3"><a href="#My-Solution-3" class="headerlink" title="My Solution:"></a>My Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">convert_to_base</span>(<span class="params">n, base</span>):</span><br><span class="line"> <span class="keyword">if</span> n == <span class="number">0</span>:</span><br><span class="line"> <span class="keyword">return</span> <span class="string">'0'</span></span><br><span class="line"> digits = []</span><br><span class="line"> <span class="keyword">while</span> n:</span><br><span class="line"> digits.append(<span class="built_in">str</span>(n % base))</span><br><span class="line"> n //= base</span><br><span class="line"> <span class="keyword">return</span> <span class="string">''</span>.join(digits[::-<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">n: <span class="built_in">int</span>, base: <span class="built_in">int</span></span>):</span><br><span class="line"> D = {}</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, n + <span class="number">1</span>):</span><br><span class="line"> D[i] = <span class="built_in">tuple</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, convert_to_base(i, base)))</span><br><span class="line"> <span class="keyword">return</span> D</span><br></pre></td></tr></table></figure><h4 id="My-Thought-Process-3"><a href="#My-Thought-Process-3" class="headerlink" title="My Thought Process:"></a>My Thought Process:</h4><ol><li><p>Helper Function <code>convert_to_base(n, base)</code>:</p><ul><li>This function converts a number <code>n</code> from base 10 to the specified base.</li><li>We use a while loop to repeatedly take the modulus (<code>n % base</code>) and append the remainder to the list <code>digits</code>.</li><li>We then divide <code>n</code> by <code>base</code> <code>(n //= base)</code> to reduce it for the next iteration.</li><li>After collecting all digits, we reverse the list and return it as a string.</li></ul></li><li><p>Main Function <code>f4(n, base)</code>:<br>We initialize an empty dictionary <code>D</code>.<br>For each number <code>i</code> from <code>0</code> to <code>n</code>, we convert <code>i</code> to the given base using <code>convert_to_base()</code>.<br>The converted base digits are then mapped to integers and stored in a tuple as the value for each key <code>i</code> in the dictionary.</p></li></ol><h3 id="Explanation-of-Why-map-is-not-Pythonic"><a href="#Explanation-of-Why-map-is-not-Pythonic" class="headerlink" title="Explanation of Why map() is not Pythonic:"></a>Explanation of Why <code>map()</code> is not Pythonic:</h3><p>In the function f4, the use of <code>map(int, convert_to_base(i, base))</code> applies the <code>int</code> function<br>to each element of the result from <code>convert_to_base</code>, effectively converting each character to an integer.</p><p>However, it’s worth noting that the <code>map()</code> function, which originates from functional programming,<br>has largely been superseded by more Pythonic constructs such as list comprehensions.</p><p>These comprehensions are generally considered superior for several reasons:</p><ul><li>They are more elegant and concise.</li><li>They tend to be shorter in terms of syntax, making the code easier to read.</li><li>They are easier to understand for most people, especially those who are more familiar with Python’s<br>standard syntax rather than functional programming constructs.</li><li>In many cases, they are also more efficient in terms of performance.</li></ul><p>For example, instead of using <code>map(int, ...)</code>, the same functionality could be achieved with a<br>list comprehension, like so:</p><p>D[i] = tuple([int(digit) for digit in convert_to_base(i, base)])</p><p>This list comprehension achieves the same result but follows a more modern Pythonic style.</p><h3 id="Standard-Solution-3"><a href="#Standard-Solution-3" class="headerlink" title="Standard Solution:"></a>Standard Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">n, base</span>):</span><br><span class="line"> D = {<span class="number">0</span>: (<span class="number">0</span>,)}</span><br><span class="line"> <span class="keyword">for</span> m <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, n + <span class="number">1</span>):</span><br><span class="line"> digits = []</span><br><span class="line"> p = m</span><br><span class="line"> <span class="keyword">while</span> p:</span><br><span class="line"> digits.append(p % base)</span><br><span class="line"> p //= base</span><br><span class="line"> D[m] = <span class="built_in">tuple</span>(<span class="built_in">reversed</span>(digits))</span><br><span class="line"> <span class="keyword">return</span> D</span><br></pre></td></tr></table></figure><p>Both solutions are valid and achieve the same result. My approach uses a helper function for base conversion, which adds modularity,<br>whereas the standard solution is more concise and directly integrates the conversion logic into the main function.</p><h1 id="Exercise-5"><a href="#Exercise-5" class="headerlink" title="Exercise 5"></a>Exercise 5</h1><p>At the first, try to run this:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(<span class="number">0.1</span> + <span class="number">0.2</span>)</span><br></pre></td></tr></table></figure><p>What happened? The result is not 0.3, but 0.30000000000000004. Why?</p><h3 id="Problem-Description-4"><a href="#Problem-Description-4" class="headerlink" title="Problem Description:"></a>Problem Description:</h3><p>The approach we are using in this exercise is designed to expose the limitations of floating-point arithmetic in computers. Let’s break down why this approach leads to precision inaccuracies and why other methods might not reveal these issues as clearly.</p><p>This problem can seem complex, and it’s designed to highlight the subtleties of floating-point arithmetic. Let’s walk through the logic using the test cases to figure out what the function does.</p><h3 id="Key-Concepts"><a href="#Key-Concepts" class="headerlink" title="Key Concepts:"></a>Key Concepts:</h3><ul><li><strong>Floating-point numbers</strong>: Computers store floating-point numbers using a binary format, which often introduces precision errors.</li><li><strong>Precision</strong>: We’re working with two types of precision in this function—simple precision (same as the length of the fractional part) and double precision (twice that length).</li></ul><h3 id="Solution"><a href="#Solution" class="headerlink" title="Solution:"></a>Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">integral_part, fractional_part</span>):</span><br><span class="line"> <span class="comment"># Calculate the number of digits in the fractional part</span></span><br><span class="line"> precision = <span class="built_in">len</span>(<span class="built_in">str</span>(fractional_part))</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Concatenate the integral and fractional parts as strings, then convert to a float</span></span><br><span class="line"> a_float = <span class="built_in">float</span>(<span class="built_in">str</span>(integral_part) + <span class="string">'.'</span> + <span class="built_in">str</span>(fractional_part))</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Format the float with precision equal to the number of digits in the fractional part (simple precision)</span></span><br><span class="line"> simple_precision = <span class="string">f'<span class="subst">{a_float:.{precision}</span>f}'</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Append a number of zeros equal to the fractional part length to the simple precision value (extended precision)</span></span><br><span class="line"> extended_simple_precision = simple_precision + <span class="string">'0'</span> * precision</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Format the float with precision equal to twice the number of fractional digits (double precision)</span></span><br><span class="line"> double_precision = <span class="string">f'<span class="subst">{a_float:.{precision * <span class="number">2</span>}</span>f}'</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Print the first part of the output</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'With'</span>, precision * <span class="number">2</span>, <span class="string">'digits after the decimal point, '</span>, end=<span class="string">''</span>)</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Compare if extended precision and double precision values are the same</span></span><br><span class="line"> <span class="keyword">if</span> extended_simple_precision == double_precision:</span><br><span class="line"> <span class="comment"># If they are the same, it means the float is precise and has trailing zeros</span></span><br><span class="line"> <span class="built_in">print</span>(simple_precision, <span class="string">'prints out with'</span>, precision, <span class="string">'trailing'</span>,</span><br><span class="line"> precision == <span class="number">1</span> <span class="keyword">and</span> <span class="string">'zero,'</span> <span class="keyword">or</span> <span class="string">'zeroes,'</span>, <span class="string">'namely, as'</span>,</span><br><span class="line"> extended_simple_precision</span><br><span class="line"> )</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> <span class="comment"># If not, there is a precision error, and no trailing zeros</span></span><br><span class="line"> <span class="built_in">print</span>(simple_precision, <span class="string">'prints out as'</span>, double_precision)</span><br></pre></td></tr></table></figure><p>Our function attempts to check and display this floating point error with simple precision (<code>simple_precision</code>) and double precision (<code>double_precision</code>). The error becomes more obvious when we represent floating point numbers with higher precision (double the number of decimal places). So in this way, we show that floating point numbers are not always actually stored as we expect them to be with more precise representation.</p><h1 id="Exercise-6"><a href="#Exercise-6" class="headerlink" title="Exercise 6"></a>Exercise 6</h1><h3 id="Problem-Description-5"><a href="#Problem-Description-5" class="headerlink" title="Problem Description:"></a>Problem Description:</h3><p>In this task, we are given:</p><ul><li>A list <code>L</code>, which contains multiple sub-lists of integers, and all sub-lists have the same length <code>n</code>.</li><li>A list <code>fields</code>, which is a permutation of <code>{1, ..., n}</code>.</li></ul><p>We are required to sort the list L by using a multi-key sorting mechanism, where:</p><ul><li>First, the elements in <code>L</code> are sorted based on the position given by the first element of <code>fields</code>.</li><li>If two sub-lists are equal based on the first field, we move to the second field, and so on.</li><li>Finally, if required, the sorting proceeds up to the last field in <code>fields</code>.</li></ul><h3 id="Example-of-Fields-Explanation"><a href="#Example-of-Fields-Explanation" class="headerlink" title="Example of Fields Explanation:"></a>Example of Fields Explanation:</h3><p>If <code>fields = [2, 1]</code>, it means:</p><ol><li>First, sort based on the second element of each sublist.</li><li>If there are ties (same values in the second position), sort based on the first element.</li></ol><h3 id="My-Solution-4"><a href="#My-Solution-4" class="headerlink" title="My Solution:"></a>My Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">L, fields</span>):</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">sorted</span>(L, key=<span class="keyword">lambda</span> x: [x[i-<span class="number">1</span>] <span class="keyword">for</span> i <span class="keyword">in</span> fields])</span><br></pre></td></tr></table></figure><ol><li><p>Sorting with sorted():<br>The <code>sorted()</code> function is used to sort the list <code>L</code>.<br>The key parameter defines how the sorting will be performed.</p></li><li><p>Lambda Function:<br>The lambda function defines how the sublists will be sorted. It generates a list of values for each sublist based on the positions specified in <code>fields</code>.<br>For example, if <code>fields = [2, 1]</code>, the lambda function will extract the second and first elements from each sublist in that order, and sorting will be done based on this new list.</p></li><li><p>Key Structure:<br>The key is a list of elements from each sublist, indexed by the positions specified in fields. We use <code>x[i - 1]</code> because fields is <code>1-based</code>, and list indexing in Python is <code>0-based</code>.</p></li><li><p>What is Lambda Function?</p></li></ol><p>For example:</p><p>We have:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">f = <span class="keyword">lambda</span> x: x * x</span><br></pre></td></tr></table></figure><p>This is equivalent to:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f</span>(<span class="params">x</span>):</span><br><span class="line"> <span class="keyword">return</span> x * x</span><br></pre></td></tr></table></figure><p>And lambda function in a sorted function is used to define a custom sorting key.</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">L = [(<span class="number">1</span>,<span class="number">2</span>), (<span class="number">3</span>,<span class="number">1</span>), (<span class="number">5</span>,<span class="number">0</span>)]</span><br><span class="line"></span><br><span class="line">SortedL = <span class="built_in">sorted</span>(L, key=<span class="keyword">lambda</span> x: x[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(SortedL)</span><br></pre></td></tr></table></figure><p>The result is: <code>[(5, 0), (3, 1), (1, 2)]</code>, it sorts the list based on the second element of each tuple.</p><h3 id="Standard-Solution-4"><a href="#Standard-Solution-4" class="headerlink" title="Standard Solution:"></a>Standard Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">L, fields</span>):</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">sorted</span>(L, key=<span class="keyword">lambda</span> x: <span class="built_in">tuple</span>(x[i - <span class="number">1</span>] <span class="keyword">for</span> i <span class="keyword">in</span> fields))</span><br></pre></td></tr></table></figure><p><strong>Why Use a Tuple?</strong>:</p><ul><li>Tuples are often preferred for multi-key sorting because they are immutable, and Python’s built-in sorting functions can efficiently compare tuples.</li><li>Each sublist is transformed into a tuple of its elements based on the order defined by fields. The sorted() function then uses these tuples to sort the list.</li></ul>]]></content>
<summary type="html"><h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="Problem-Description"><a href="#Pr</summary>
<category term="9021" scheme="https://longsizhuo.github.io/tags/9021/"/>
<category term="lab" scheme="https://longsizhuo.github.io/tags/lab/"/>
</entry>
<entry>
<title>9021_TUT_2</title>
<link href="https://longsizhuo.github.io/post/becdc081.html"/>
<id>https://longsizhuo.github.io/post/becdc081.html</id>
<published>2024-10-03T08:57:12.472Z</published>
<updated>2024-10-03T08:57:12.472Z</updated>
<content type="html"><![CDATA[<h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1:"></a>Exercise 1:</h1><p>This exercise focuses on input validation and formatting floating-point numbers. The goal is to prompt the user to enter a floating-point number between -1 and 1 (exclusive). If the input is valid, the program rounds the number to two decimal places and prints it. Otherwise, it keeps prompting the user until a valid input is provided.<br>Key Points:</p><ul><li>The program uses a try-except block to catch invalid inputs (e.g., strings that cannot be converted to floats).</li><li>The input() function is wrapped in an infinite while loop to continuously ask for input until the correct condition is met.</li></ul><p>In the updated version of Exercise 1, we use the formatting :.2f instead of round(). Here’s the key difference between the two:</p><ul><li><code>round()</code>: This is a Python built-in function that rounds a number to a specified number of decimal places. For example, round(1.236, 2) will return 1.24. However, the output of round() is still a float, but it does not guarantee a fixed number of decimal places when printed. For instance, round(1.0001, 2) would return 1.0 and only display one decimal place, not two.</li><li><code>:.2f</code>: This is part of Python’s string formatting and ensures the number is displayed with exactly two decimal places, no matter what the number is. It also rounds the number appropriately. For instance, number = 1.0 formatted as f”{number:.2f}” will print 1.00. This makes :.2f particularly useful for consistent display of decimal places, which is important for formatting output for users.</li></ul><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line"> <span class="keyword">try</span>:</span><br><span class="line"> i = <span class="built_in">input</span>(<span class="string">'Enter a floating point number between -1 and 1 excluded: '</span>)</span><br><span class="line"> number = <span class="built_in">float</span>(i)</span><br><span class="line"> <span class="keyword">if</span> <span class="string">'.'</span> <span class="keyword">not</span> <span class="keyword">in</span> i:</span><br><span class="line"> <span class="keyword">raise</span> ValueError</span><br><span class="line"> <span class="keyword">if</span> -<span class="number">1</span> < number < <span class="number">1</span>:</span><br><span class="line"> <span class="comment"># not using round() here because it rounds to the nearest even number</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f'\nUp to +/-0.005, you input <span class="subst">{number:<span class="number">.2</span>f}</span>'</span>)</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> <span class="keyword">raise</span> ValueError</span><br><span class="line"> <span class="keyword">break</span></span><br><span class="line"> <span class="keyword">except</span> ValueError:</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">"You got that wrong, try again!\n"</span>)</span><br></pre></td></tr></table></figure><h1 id="Exercise-2"><a href="#Exercise-2" class="headerlink" title="Exercise 2:"></a>Exercise 2:</h1><p>This exercise involves processing a block of text and formatting it into sentences. Each sentence should have its first word capitalized, and the remaining words should be in lowercase. The task is to handle spaces and punctuation properly.</p><p>Key Points:</p><ul><li>A regular expression (re.sub) is used to replace multiple spaces with a single space.</li><li>Another regular expression (re.split) is used to split the text into sentences while preserving punctuation marks.</li><li>After splitting, the sentences are processed: the first word is capitalized, and all other words are made lowercase.</li><li>Finally, the processed sentences are recombined into a single formatted text.</li></ul><h3 id="Why-use-re-in-Exercise-2-and-what-is-re"><a href="#Why-use-re-in-Exercise-2-and-what-is-re" class="headerlink" title="Why use re in Exercise 2, and what is re?"></a>Why use re in Exercise 2, and what is re?</h3><p>In Exercise 2, we use re (Python’s regular expression module) to process and format the text input. Let’s break down why re is used and what it is:</p><h3 id="What-is-re"><a href="#What-is-re" class="headerlink" title="What is re?"></a>What is re?</h3><p>re stands for regular expressions, which are powerful tools for matching patterns in strings. The re module in Python allows you to work with regular expressions to search, split, and manipulate text based on specific patterns. Regular expressions are highly flexible and efficient for handling complex string operations.</p><h3 id="Why-use-re-in-Exercise-2"><a href="#Why-use-re-in-Exercise-2" class="headerlink" title="Why use re in Exercise 2?"></a>Why use re in Exercise 2?</h3><p>In this exercise, we need to handle several complex text manipulations:</p><ol><li>Replace multiple spaces with a single space: Sentences in the text may have irregular spaces between words, so we need to normalize these spaces. Instead of writing loops or conditions to handle each case, we use re.sub() with a pattern r’\s+’ to easily match all occurrences of one or more spaces and replace them with a single space.</li><li>Split sentences while preserving punctuation: We need to split the text into individual sentences, where each sentence is followed by punctuation (e.g., ‘.’, ‘!’, or ‘?’). The function re.split(r’([.!?])’, text) allows us to split the text based on punctuation while keeping the punctuation marks, which is crucial for proper sentence reconstruction.</li></ol><p>Regular expressions allow us to:</p><ul><li>Efficiently match patterns like spaces or punctuation.</li><li>Perform complex text transformations with minimal code.</li><li>Handle edge cases that would otherwise require more manual handling.</li></ul><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Assume that the argument text is a string that denotes a text,</span></span><br><span class="line"><span class="comment"># defined as one or more sentences, two successive</span></span><br><span class="line"><span class="comment"># sentences being separated by at least one space,</span></span><br><span class="line"><span class="comment"># the first sentence being possibly preceded with spaces,</span></span><br><span class="line"><span class="comment"># the last sentence being possibly followed by spaces,</span></span><br><span class="line"><span class="comment"># a sentence being defined as at least two words,</span></span><br><span class="line"><span class="comment"># two successive words in a sentence being separated by</span></span><br><span class="line"><span class="comment"># at least one space, a word being defined as a sequence</span></span><br><span class="line"><span class="comment"># of (uppercase or lowercase) letters,</span></span><br><span class="line"><span class="comment"># - possibly followed by a comma for a word that is</span></span><br><span class="line"><span class="comment"># not the last one in its sentence,</span></span><br><span class="line"><span class="comment"># - definitely followed by a full stop, an exclamation mark</span></span><br><span class="line"><span class="comment"># or a question mark for a word that is the last one</span></span><br><span class="line"><span class="comment"># in its sentence.</span></span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">text</span>):</span><br><span class="line"> <span class="comment"># Use regular expression to replace multiple spaces with a single space</span></span><br><span class="line"> text = re.sub(<span class="string">r'\s+'</span>, <span class="string">' '</span>, text.strip())</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Correct way to split sentences while preserving delimiters</span></span><br><span class="line"> sentences = re.split(<span class="string">r'([.!?])'</span>, text)</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Process sentences and punctuation separately</span></span><br><span class="line"> new_text = []</span><br><span class="line"> i = <span class="number">0</span></span><br><span class="line"> <span class="keyword">while</span> i < <span class="built_in">len</span>(sentences)-<span class="number">1</span>:</span><br><span class="line"> sentence = sentences[i].strip()</span><br><span class="line"> <span class="keyword">if</span> sentence:</span><br><span class="line"> sentence =<span class="string">' '</span>.join(sentence.capitalize().split())</span><br><span class="line"> <span class="comment"># Rebuild the sentence and add back the punctuation</span></span><br><span class="line"> new_text.append(sentence +sentences[i +<span class="number">1</span>])</span><br><span class="line"> i += <span class="number">2</span></span><br><span class="line"> <span class="keyword">return</span> <span class="string">' '</span>.join(new_text)</span><br></pre></td></tr></table></figure><h1 id="Exercise-3"><a href="#Exercise-3" class="headerlink" title="Exercise 3:"></a>Exercise 3:</h1><p>This exercise works with lists of integers and aims to repeatedly remove the first and last elements of the list as long as they are equal. The list is treated as a double-ended queue (deque) for efficient removal of elements from both ends.</p><p>Key Points:</p><ul><li>The deque data structure is used because it provides O(1) operations for popping elements from both ends, which is more efficient than using lists.</li><li>The program checks if the first and last elements of the deque are equal and removes them until this condition is no longer met.</li><li>The deque is converted back to a list before being returned.</li></ul><h3 id="Why-is-deque-more-efficient-than-list-in-Exercise-3"><a href="#Why-is-deque-more-efficient-than-list-in-Exercise-3" class="headerlink" title="Why is deque more efficient than list in Exercise 3?"></a>Why is <code>deque</code> more efficient than <code>list</code> in Exercise 3?</h3><p>In Exercise 3, we are frequently removing elements from both the front (left) and the back (right) of the list. This is where using a deque (double-ended queue) from Python’s collections module becomes more efficient compared to using a standard list.</p><p>Here’s why:</p><ul><li><p>List Behavior: When you use a standard list and call list.pop(0) to remove the first (leftmost) element, it requires shifting all the remaining elements one position to the left. This shift operation takes linear time—O(n), where n is the number of elements in the list. This means that for every removal from the front, the larger the list, the slower the operation becomes.</p><ul><li>Removing from the right side of a list using list.pop() is an O(1) operation (constant time) because no elements need to be shifted, making it efficient only when working from the end of the list.</li></ul></li><li><p>Deque Behavior: A deque (double-ended queue) is specifically designed to support efficient append and pop operations from both ends. In a deque, both popleft() and pop() operations take constant time—O(1)—because the deque is implemented as a doubly linked list. This means no elements need to be shifted when popping from the left or right.</p><ul><li>In Exercise 3, where we need to frequently remove elements from both ends of the list, using a deque ensures that both the removal from the left (popleft()) and the right (pop()) are performed in constant time. This makes the entire process much more efficient, especially for large lists where repeated operations would slow down if we used a standard list.</li></ul></li></ul><h3 id="What-is-a-deque"><a href="#What-is-a-deque" class="headerlink" title="What is a deque?"></a>What is a <code>deque</code>?</h3><p>A deque (short for “double-ended queue”) is a data structure that allows for fast appending and popping of elements from both ends. It is part of the collections module in Python and is optimized for scenarios where you need to efficiently add or remove elements from both ends of the sequence.</p><h3 id="Key-Features-of-deque"><a href="#Key-Features-of-deque" class="headerlink" title="Key Features of deque:"></a>Key Features of <code>deque</code>:</h3><ul><li><code>O(1)</code> time complexity for operations on both ends (append, pop, appendleft, popleft).</li><li>It is implemented as a <strong>doubly linked list</strong>, meaning each element contains a reference to both the previous and next elements, allowing efficient traversal in both directions.</li><li><code>deque</code> is ideal for scenarios where you need frequent and efficient insertions and removals from both the front and back of a sequence, unlike a standard list where such operations are costly at the front.</li></ul><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Assume that the argument L is a list of integers.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># For as long as the list has at least two elements</span></span><br><span class="line"><span class="comment"># and the first and last elements of the list are equal,</span></span><br><span class="line"><span class="comment"># pop out those elements.</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># def f3(L):</span></span><br><span class="line"><span class="comment"># # Remove the list as long as it has at least two elements and the first and last elements are equal</span></span><br><span class="line"><span class="comment"># while len(L) > 1 and L[0] == L[-1]:</span></span><br><span class="line"><span class="comment"># L.pop(0) # Remove the first element</span></span><br><span class="line"><span class="comment"># L.pop(-1) # Remove the last element</span></span><br><span class="line"><span class="comment"># return L</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> deque</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">L</span>):</span><br><span class="line"> L = deque(L) <span class="comment"># Convert the list to a deque for efficient popping from both ends</span></span><br><span class="line"> <span class="comment"># Continue removing elements while there are at least two elements and the first and last are equal</span></span><br><span class="line"> <span class="keyword">while</span> <span class="built_in">len</span>(L) > <span class="number">1</span> <span class="keyword">and</span> L[<span class="number">0</span>] == L[-<span class="number">1</span>]:</span><br><span class="line"> L.popleft() <span class="comment"># Efficiently remove the first element (O(1) operation)</span></span><br><span class="line"> L.pop() <span class="comment"># Efficiently remove the last element (O(1) operation)</span></span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">list</span>(L) <span class="comment"># Convert the deque back to a list and return it</span></span><br></pre></td></tr></table></figure><h1 id="Exercise-4"><a href="#Exercise-4" class="headerlink" title="Exercise 4:"></a>Exercise 4:</h1><p>This exercise deals with lists of integers that are in increasing order. The goal is to remove any element whose value is equal to its index in the list. The program iterates over the list and removes such elements, ensuring the index is correctly adjusted after each removal.</p><p>Key Points:</p><ul><li>The program uses a while loop and checks if the element at index i is equal to i. If true, it removes the element and does not increment i, so that the next element at the same position is checked.</li><li>The remove() function is used to delete the element, which is appropriate for this task.</li><li>Care is taken to ensure that index adjustments are handled correctly.</li></ul><p>The reason we use remove() instead of pop(0) or popleft() in a deque is that we need to specifically remove the value that matches the number we reached. pop() and popleft() remove elements by position, without considering the value, which isn’t suitable for our case.</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Assume that the argument L is a list of integers</span></span><br><span class="line"><span class="comment"># that forms an increasing sequence.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># For as long as some member of the list is equal to its index</span></span><br><span class="line"><span class="comment"># in the list, pop out the leftmost such member of the list.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">L</span>):</span><br><span class="line"> i = <span class="number">0</span></span><br><span class="line"> <span class="keyword">while</span> i < <span class="built_in">len</span>(L):</span><br><span class="line"> <span class="keyword">if</span> L[i] == i:</span><br><span class="line"> L.remove(L[i]) <span class="comment"># Using remove() here since popleft() removes from the left only</span></span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> i += <span class="number">1</span> <span class="comment"># Only increment i if no element was removed</span></span><br><span class="line"> <span class="keyword">return</span> L</span><br></pre></td></tr></table></figure><h1 id="Exercise-5"><a href="#Exercise-5" class="headerlink" title="Exercise 5:"></a>Exercise 5:</h1><p>This exercise works with a circular list of integers. The task is to identify elements that are both larger than one of their adjacent elements and smaller than the other. The result is returned as a dictionary where each key is such an element, and its value is a pair of the adjacent elements (one smaller and one larger).</p><p>Key Points:</p><ul><li>The list is treated as circular, meaning the first element is considered adjacent to the last element.</li><li>The program iterates through the list, compares each element with its neighbors, and stores those that meet the criteria.</li><li>For each valid element, the adjacent smaller and larger elements are stored in a dictionary.</li></ul><p>To solve this problem, we need to create a dictionary D where each key is an element in the list L that satisfies a certain condition, and the value is a tuple of two elements. The first element of this tuple is the adjacent element that is smaller than the current key, and the second element is the adjacent element that is larger than the current key.</p><p>Steps:</p><ol><li>Loop structure: Check each element.</li><li>Processing of adjacent elements: Since the list is cyclic, the previous element of the first element is the last element, and the next element of the last element is the first element.</li><li>Condition check: Find the adjacent elements that are smaller and larger than the current element, and add them to the result dictionary.</li></ol><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Assume that the argument L is a list of at least 3 distinct integers.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Returns a dictionary D whose keys are those of the members e of L,</span></span><br><span class="line"><span class="comment"># if any, that are</span></span><br><span class="line"><span class="comment"># - smaller than the element right before or right after, and</span></span><br><span class="line"><span class="comment"># - larger than the element right before or right after.</span></span><br><span class="line"><span class="comment"># It is considered that</span></span><br><span class="line"><span class="comment"># - the first member of L is right after the last member of L, and</span></span><br><span class="line"><span class="comment"># - the last member of L is right before the first member of L</span></span><br><span class="line"><span class="comment"># (as if making a ring out of the list).</span></span><br><span class="line"><span class="comment"># For a key e in D, the associated value is the pair whose</span></span><br><span class="line"><span class="comment"># first element is the member of L that is right before or right after</span></span><br><span class="line"><span class="comment"># e and smaller than e, and whose second element is the member of L</span></span><br><span class="line"><span class="comment"># that is right before or right after e and greater than e.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">L</span>):</span><br><span class="line"> D = {}</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(L)):</span><br><span class="line"> m = L[i - <span class="number">1</span>]</span><br><span class="line"> n = L[(i + <span class="number">1</span>) % <span class="built_in">len</span>(L)]</span><br><span class="line"> <span class="keyword">if</span> n < m:</span><br><span class="line"> m, n = n, m</span><br><span class="line"> <span class="keyword">if</span> m < L[i] < n:</span><br><span class="line"> D[L[i]] = m, n</span><br><span class="line"> <span class="keyword">return</span> D</span><br></pre></td></tr></table></figure><h1 id="Exercise-6"><a href="#Exercise-6" class="headerlink" title="Exercise 6:"></a>Exercise 6:</h1><p>This exercise deals with factorizing an integer n into the form 2^k * m, where m is an odd number. If n is negative, the program adds a negative sign to the output. If n is zero, it prints a special message.</p><p>Key Points:</p><ul><li>The program uses a loop to divide n by 2 until n is no longer divisible by 2, counting the number of divisions (k).</li><li>The absolute value of n is used to ensure correct handling of negative numbers, and a sign is added to the final result if the original number was negative.</li><li>The program handles the special case where n = 0 by printing a unique message.</li></ul><p>More Details:</p><ol><li>You need to express the given integer n as n = 2^k * m.<ul><li>k represents the number of times n can be divided by 2. In other words, it is the power of 2 in the factorization of n.</li><li>m is the remaining odd part after dividing out all factors of 2.</li></ul></li><li>If n is negative, the output should include a negative sign.</li><li>Special case: If n = 0, a specific message should be printed.</li><li>The result is printed directly, not returned.</li></ol><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Assume that the argument n is an integer.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># The output is printed out, not returned.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># You might find the abs() function useful.</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">n</span>):</span><br><span class="line"> <span class="keyword">if</span> n == <span class="number">0</span>:</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">"0 = 2^k * 0 for all integers k!"</span>)</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> k = <span class="number">0</span></span><br><span class="line"> ori = n</span><br><span class="line"> <span class="keyword">if</span> n < <span class="number">0</span>:</span><br><span class="line"> sign = <span class="string">'-'</span></span><br><span class="line"> n = -n</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> sign = <span class="string">''</span></span><br><span class="line"> <span class="keyword">while</span> n % <span class="number">2</span> == <span class="number">0</span>:</span><br><span class="line"> n //= <span class="number">2</span></span><br><span class="line"> k += <span class="number">1</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f"<span class="subst">{ori}</span> = <span class="subst">{sign}</span>2^<span class="subst">{k}</span> * <span class="subst">{n}</span>"</span>)</span><br><span class="line"> <span class="keyword">return</span></span><br></pre></td></tr></table></figure><p><strong>FOR VERY VERY VERY VERY VERY BIG NUMBER:</strong></p><p>When dealing with very large integers, the method of continuously dividing the number by 2 to factor out powers of 2 (2^k) can become inefficient. This is because each division can be costly in terms of computational time, especially for very large numbers with millions or billions of digits. Each division involves recalculating the entire integer, which is slow for large integers.<br>Using Bit Manipulation:</p><p>A much more efficient approach is to use <strong>bit manipulation</strong> to determine how many times a number can be divided by 2 (i.e., how many factors of 2 it has). This method avoids division altogether and instead directly analyzes the binary representation of the number to count the number of trailing zeros, which correspond to the powers of 2 in the factorization.</p><h3 id="Why"><a href="#Why" class="headerlink" title="Why?"></a>Why?</h3><ol><li><p>Bitwise operations are much faster than arithmetic operations like division, especially for large integers. Counting the trailing zeros in a number’s binary representation can be done in constant time.</p></li><li><p>Extracting the lowest set bit of a number allows us to quickly find how many times a number can be divided by 2 without having to repeatedly divide the number. This provides the power of 2 (k) directly.</p></li></ol><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">n</span>):</span><br><span class="line"> <span class="keyword">if</span> n == <span class="number">0</span>:</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">"0 = 2^k * 0 for all integers k!"</span>)</span><br><span class="line"> <span class="keyword">return</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Handle negative sign</span></span><br><span class="line"> sign = <span class="string">'-'</span> <span class="keyword">if</span> n < <span class="number">0</span> <span class="keyword">else</span> <span class="string">''</span></span><br><span class="line"> n = <span class="built_in">abs</span>(n)</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Using bit manipulation to count how many trailing zeros (powers of 2)</span></span><br><span class="line"> k = (n & -n).bit_length() - <span class="number">1</span> <span class="comment"># Count trailing zeros by isolating the lowest set bit</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Remove 2^k factor from n</span></span><br><span class="line"> m = n >> k <span class="comment"># Equivalent to n // 2^k, shifting right by k bits</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># Print the result</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f"<span class="subst">{sign}</span><span class="subst">{n}</span> = <span class="subst">{sign}</span>2^<span class="subst">{k}</span> * <span class="subst">{m}</span>"</span>)</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1:"></a>Exercise 1:</h1><p>This exercise focuses on input valid</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="Tutorial" scheme="https://longsizhuo.github.io/tags/Tutorial/"/>
</entry>
<entry>
<title>9021_TUT_4</title>
<link href="https://longsizhuo.github.io/post/9ba69f5d.html"/>
<id>https://longsizhuo.github.io/post/9ba69f5d.html</id>
<published>2024-09-30T14:00:00.000Z</published>
<updated>2024-10-22T05:06:02.499Z</updated>
<content type="html"><![CDATA[<h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="Problem-Description"><a href="#Problem-Description" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>At first, I thought this exercise was about dividing by a modulus, where the modulus would always be incremented by one. But then I realized that in some cases, there’s no “2” in the division sequence. For example, for <code>12</code>, the answer is <code>12 6 3 1\n</code>. This indicates that the number is always being divided by <code>2</code>.</p><p>When we look at the examples of these answers, we can see that the format aligns each number to the right, based on the width of the largest number.</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">%</span><span class="language-bash">%run_and_test python3 -c <span class="string">"from exercise_4_1 import f1; f1(13)"</span></span></span><br><span class="line"></span><br><span class="line">'''</span><br><span class="line"> 13 6 3 1\n</span><br><span class="line"> 12 6 3 1\n</span><br><span class="line"> 11 5 2 1\n</span><br><span class="line"> 10 5 2 1\n</span><br><span class="line"> 9 4 2 1\n</span><br><span class="line"> 8 4 2 1\n</span><br><span class="line"> 7 3 1\n</span><br><span class="line"> 6 3 1\n</span><br><span class="line"> 5 2 1\n</span><br><span class="line"> 4 2 1\n</span><br><span class="line"> 3 1\n</span><br><span class="line"> 2 1\n</span><br><span class="line"> 1\n</span><br><span class="line">'''</span><br></pre></td></tr></table></figure><p>So we have the following solution:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Assume that the argument n is an integer at least equal to 1.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Each integer is printed out in a field of size equal to</span></span><br><span class="line"><span class="comment"># the number of digits in n plus 1.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># The output is printed out, not returned.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">n</span>):</span><br><span class="line"> w = <span class="built_in">len</span>(<span class="built_in">str</span>(n)) + <span class="number">1</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n, <span class="number">0</span>, -<span class="number">1</span>):</span><br><span class="line"> <span class="keyword">while</span> i:</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f'<span class="subst">{i:{w}</span>}'</span>, end=<span class="string">""</span>)</span><br><span class="line"> i = i // <span class="number">2</span></span><br><span class="line"> <span class="built_in">print</span>()</span><br><span class="line"> <span class="keyword">return</span></span><br></pre></td></tr></table></figure><h3 id="Complexity-Analysis"><a href="#Complexity-Analysis" class="headerlink" title="Complexity Analysis"></a>Complexity Analysis</h3><p>The time complexity of this algorithm is <code>O(n log n)</code>, where <code>n</code> is the input number. This is because we are dividing the number by <code>2</code> until we reach <code>1</code>. The space complexity is <code>O(1)</code> because we are not using any additional data structures.</p><h1 id="Exercise-2"><a href="#Exercise-2" class="headerlink" title="Exercise 2"></a>Exercise 2</h1><h3 id="Problem-Description-1"><a href="#Problem-Description-1" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>This exercise asks us to repeatedly remove the maximum number from the set until only one element remains. The line print(“A list of sets:”, all(isinstance(x, set) for x in S)) checks if the return value of f2 is a list of sets.</p><h3 id="In-my-solution"><a href="#In-my-solution" class="headerlink" title="In my solution:"></a>In my solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">S: <span class="built_in">set</span>[<span class="built_in">int</span>]</span>):</span><br><span class="line"> ans = []</span><br><span class="line"> s_list = <span class="built_in">list</span>(S) <span class="comment"># Convert the set to a list</span></span><br><span class="line"> s_list.sort() <span class="comment"># Sort the list</span></span><br><span class="line"> <span class="keyword">while</span> <span class="built_in">len</span>(s_list) > <span class="number">0</span>:</span><br><span class="line"> ans.append(<span class="built_in">set</span>(s_list)) <span class="comment"># Append the current set</span></span><br><span class="line"> s_list.pop() <span class="comment"># Pop the last (largest) element</span></span><br><span class="line"> <span class="keyword">return</span> ans</span><br></pre></td></tr></table></figure><p>I convert the set to a list because tuples don’t have a sort() method. So I convert it, sort it, and then pop the largest element (which is at the end of the list) while the length is greater than 1.</p><h3 id="The-standard-solution-is"><a href="#The-standard-solution-is" class="headerlink" title="The standard solution is:"></a>The standard solution is:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">S</span>):</span><br><span class="line"> U = [<span class="built_in">set</span>(S)]</span><br><span class="line"> <span class="keyword">while</span> <span class="built_in">len</span>(S) > <span class="number">1</span>:</span><br><span class="line"> S.remove(<span class="built_in">max</span>(S)) <span class="comment"># Remove the maximum element</span></span><br><span class="line"> U.append(<span class="built_in">set</span>(S)) <span class="comment"># Append the current set</span></span><br><span class="line"> <span class="keyword">return</span> U</span><br></pre></td></tr></table></figure><p>The standard solution is simpler; it uses max() to find and remove the largest element, then appends the result to the list.</p><p>Standard solution is better because it is more concise and uses less memory.</p><h1 id="Exercise-3"><a href="#Exercise-3" class="headerlink" title="Exercise 3"></a>Exercise 3</h1><h3 id="Problem-Description-2"><a href="#Problem-Description-2" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>As per the description of Exercise 4, we need to remove elements that are equal to the mean value of their neighboring elements (i.e., the element is the average of the one just before and the one just after it).<br>Please pay attention to the special challenge: use only one loop without any break or continue statements, and only one if statement (with no elif nor else statements).</p><h3 id="In-my-solution-1"><a href="#In-my-solution-1" class="headerlink" title="In my solution:"></a>In my solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Assume that the argument L is an increasing list of integers.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Keep removing any member of the list</span></span><br><span class="line"><span class="comment"># that is neither the first one nor the last one</span></span><br><span class="line"><span class="comment"># and that is the average of the one just before and the one just after.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Special challenge: use only one loop without any break or continue statements,</span></span><br><span class="line"><span class="comment"># and only one if statement (with no elif nor else statements).</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">L</span>):</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(L) - <span class="number">2</span>):</span><br><span class="line"> <span class="keyword">if</span> L[i] + L[i + <span class="number">2</span>] == <span class="number">2</span> * L[i + <span class="number">1</span>]: <span class="comment"># Check if the middle element is the average</span></span><br><span class="line"> L.pop(i + <span class="number">1</span>) <span class="comment"># Remove the element if it satisfies the condition</span></span><br><span class="line"> <span class="keyword">return</span> f3(L) <span class="comment"># Recurse to check the rest of the list</span></span><br><span class="line"> <span class="keyword">return</span> L</span><br></pre></td></tr></table></figure><p><strong>Explanation</strong>:</p><ul><li><p>The function iterates through the list, checking if any element (except the first and last) is the average of its neighbors.</p></li><li><p>If an element meets this condition, it’s removed using <code>pop()</code>, and the function calls itself recursively to continue checking the remaining list.</p></li><li><p>This approach ensures that all elements satisfying the condition are removed.</p></li><li><p>The main reason for using <strong>recursion</strong> in the original code is to avoid <code>i</code> going beyond the scope of the list, because the length of the list changes each time an element is deleted, so in the original for loop, the index may exceed the length of the list. Recursion avoids this situation by re-calling the function and re-traversing the list from the beginning.</p></li></ul><p>When we use <code>for i in sth.</code> in Python, <code>i</code> is essentially a “view” or a “shallow copy” of the elements in <code>sth.</code>. Modifying <code>i</code> directly will not change <code>sth.</code> itself. Additionally, we cannot modify the value of <code>i</code>, because in each iteration of the loop, <code>i</code> is reset to the next element in the sequence.<br>This means that if we use a for loop directly in this context, and we remove an element from the list during the loop, the list will get shorter. As a result, <code>i</code> could end up being out of range in subsequent iterations of the loop.</p><h3 id="The-standard-solution-is-1"><a href="#The-standard-solution-is-1" class="headerlink" title="The standard solution is:"></a>The standard solution is:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">L</span>):</span><br><span class="line"> i = <span class="number">0</span></span><br><span class="line"> <span class="keyword">while</span> (i := i + <span class="number">1</span>) < <span class="built_in">len</span>(L) - <span class="number">1</span>:</span><br><span class="line"> <span class="keyword">if</span> L[i - <span class="number">1</span>] + L[i + <span class="number">1</span>] == L[i] * <span class="number">2</span>:</span><br><span class="line"> L.pop(i)</span><br><span class="line"> i -= <span class="number">1</span></span><br><span class="line"> <span class="keyword">return</span> L</span><br></pre></td></tr></table></figure><p><strong>Explanation</strong>:</p><p>The while loop version of the code does avoid recursion, and manually manages the value of i to ensure that the index does not exceed the range after the list is deleted. This reduces the complexity of the recursive call while achieving the same effect.</p><p><strong>Key points</strong>:</p><ul><li>The function uses only one loop and one if statement as required by the challenge.</li><li>Recursion is used to continue processing after each removal.</li></ul><h1 id="Exercise-4"><a href="#Exercise-4" class="headerlink" title="Exercise 4"></a>Exercise 4</h1><h3 id="Problem-Description-3"><a href="#Problem-Description-3" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>You are given an integer <code>n</code>, and the goal is to express <code>n</code> as a sum (or difference) of powers of <code>2</code>. This should be done by leveraging the binary representation of <code>n</code>.<br>Specifically, you need to:</p><ol><li>Convert n to its binary form.</li><li>Identify which positions in the binary form have a 1.</li><li>Use these positions to generate the corresponding powers of 2.</li><li>If n is positive, add the powers of 2 together. If n is negative, subtract the powers of 2.<br>The output should be in the form of an equation, displaying the original number as the sum (or difference) of powers of 2.</li></ol><h4 id="Example-1"><a href="#Example-1" class="headerlink" title="Example 1:"></a>Example 1:</h4><p>For <code>n = 13</code>:</p><p>The binary representation of 13 is 1101.<br>This corresponds to <code>2^3</code> + <code>2^2</code> + <code>2^0</code>, because the 3rd, 2nd, and 0th positions in the binary number are <code>1</code>.</p><p>Output: <code>13 = 2^3 + 2^2 + 2^0</code></p><h3 id="Explanation"><a href="#Explanation" class="headerlink" title="Explanation:"></a>Explanation:</h3><p>The function f4(n) converts an integer n into a sum of powers of 2 based on its binary representation. Let’s go through the code:</p><ol><li><p>Handling the case when n is zero:</p> <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> <span class="keyword">not</span> n:</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'0 = 0'</span>)</span><br><span class="line"> <span class="keyword">return</span></span><br></pre></td></tr></table></figure><p> This part checks <code>if n is zero</code> using if not n. If <code>n</code> is zero, the function prints <code>0 = 0</code> and returns immediately, since zero doesn’t need further decomposition into powers of <code>2</code>.</p></li><li><p>Converting the number to binary:</p> <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">binary_n = <span class="string">f'<span class="subst">{n:b}</span>'</span></span><br></pre></td></tr></table></figure><p>The <code>f'{n:b}'</code> converts the integer <code>n</code> to its binary form as a string (without the <code>0b</code> prefix). For example, if <code>n = 13</code>, <code>binary_n</code> will be <code>1101</code>.</p></li><li><p>Finding the positions of 1s in the binary representation:</p> <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">powers = (i <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(binary_n)) <span class="keyword">if</span> binary_n[i] == <span class="string">'1'</span>)</span><br></pre></td></tr></table></figure><p> This list comprehension creates a list of indices where the binary digit is <code>1</code>. For <code>1101</code>, the <code>positions</code> list will be <code>[0, 2, 3]</code>.</p><ul><li>This is a generator expression that finds the positions (indices) in the binary string where there is a <code>1</code>.</li><li><code>range(len(binary_n))</code> iterates over each character in the binary string, and the condition <code>binary_n[i] == '1'</code>filters out the positions where there is a <code>1</code>.</li><li>For example, if <code>n = 13</code> and <code>binary_n = '1101'</code>, the positions of 1s would be <code>(0, 2, 3)</code>, because the first, third, and fourth bits from the right are <code>1</code>.</li></ul></li><li><p>print(operator.join(f’2^{len(binary_n) - i - 1}’ for i in powers))</p> <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(operator.join(<span class="string">f'2^<span class="subst">{<span class="built_in">len</span>(binary_n) - i - <span class="number">1</span>}</span>'</span> <span class="keyword">for</span> i <span class="keyword">in</span> powers))</span><br></pre></td></tr></table></figure><ul><li>This is the key part of the function that prints the powers of 2 based on the positions of 1s in the binary representation.<ul><li><code>f'2^{len(binary_n) - i - 1}'</code> creates strings like<code> 2^3</code>, <code>2^2</code>, <code>2^0</code> by converting each position i into the corresponding exponent for 2. The exponent is calculated as len(binary_n) - i - 1, where i is the position of the 1 in the binary string.</li><li><code>operator.join(...)</code> joins all these terms together with either<code>' + '</code>or<code>' - '</code>depending on the value of <code>n</code>.</li></ul></li></ul></li></ol><h1 id="Exercise-5"><a href="#Exercise-5" class="headerlink" title="Exercise 5"></a>Exercise 5</h1><p>To solve next problems, lets first understand the <code>zip</code> function in Python. </p><ol><li>Let’s try:</li></ol><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">L1 = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line">L2 = [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(<span class="built_in">zip</span>(L1, L2)))</span><br></pre></td></tr></table></figure><p>Output:</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[(1, 4), (2, 5), (3, 6)]</span><br></pre></td></tr></table></figure><p>And <code>zip</code> in dictionary:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">L1 = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line">L2 = [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dict</span>(<span class="built_in">zip</span>(L1, L2)))</span><br></pre></td></tr></table></figure><p>Output:</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[(1, 4), (2, 5), (3, 6)]</span><br><span class="line">{1: 4, 2: 5, 3: 6}</span><br></pre></td></tr></table></figure><p>The finally we try using <code>zip</code> with <code>*</code>, which is used to unpack the elements of a list or tuple:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">L = [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>], [<span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>]]</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">zip</span>(L):</span><br><span class="line"> <span class="built_in">print</span>(i)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">zip</span>(*L):</span><br><span class="line"> <span class="built_in">print</span>(i)</span><br></pre></td></tr></table></figure><p>Output:</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">([1, 2, 3],)</span><br><span class="line">([4, 5, 6],)</span><br><span class="line">([7, 8, 9],)</span><br><span class="line">(1, 4, 7)</span><br><span class="line">(2, 5, 8)</span><br><span class="line">(3, 6, 9)</span><br></pre></td></tr></table></figure><h3 id="Problem-Description-4"><a href="#Problem-Description-4" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>In this problem, we can identify the pattern by observing the example: start from the first and last elements of a list and progressively make pairs towards the center of the list.</p><p>My initial thought was to use a two-pointer approach: one pointer starts at the beginning of the list, and the other starts at the end, and they move towards each other. However, I missed the specific requirement in the problem: “Return an expression built only from list, reversed, and zip.”</p><h3 id="Wrong-Solution"><a href="#Wrong-Solution" class="headerlink" title="Wrong Solution:"></a>Wrong Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">*L</span>):</span><br><span class="line"> ans = []</span><br><span class="line"> left = <span class="number">0</span></span><br><span class="line"> right = <span class="built_in">len</span>(L) - <span class="number">1</span></span><br><span class="line"> <span class="keyword">while</span> left < <span class="built_in">len</span>(L):</span><br><span class="line"> ans.append(((L[left], L[right]), (L[right], L[left])))</span><br><span class="line"> left += <span class="number">1</span></span><br><span class="line"> right -= <span class="number">1</span></span><br><span class="line"> <span class="keyword">return</span> ans</span><br></pre></td></tr></table></figure><h3 id="Correct-Solution"><a href="#Correct-Solution" class="headerlink" title="Correct Solution:"></a>Correct Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">*L</span>):</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">list</span>(<span class="built_in">zip</span>(<span class="built_in">zip</span>(L, <span class="built_in">reversed</span>(L)), <span class="built_in">reversed</span>(<span class="built_in">list</span>(<span class="built_in">zip</span>(L, <span class="built_in">reversed</span>(L))))))</span><br></pre></td></tr></table></figure><p>The idea behind the correct solution is as follows:</p><ol><li><p><code>zip(L, reversed(L))</code> creates pairs of elements where the first comes from <code>L</code> and the second comes from <code>reversed(L)</code> (i.e., <code>L</code> reversed).<br>Example: If <code>L = (1, 2, 3)</code>, then <code>reversed(L)</code> is <code>(3, 2, 1)</code>. So, <code>zip(L, reversed(L))</code> results in <code>[(1, 3), (2, 2), (3, 1)]</code>.</p></li><li><p><code>reversed(list(zip(L, reversed(L))))</code>: Here, we convert the result of <code>zip(L, reversed(L))</code> into a list and then reverse the entire list.<br>Example: If <code>zip(L, reversed(L))</code> produced <code>[(1, 3), (2, 2), (3, 1)]</code>, then <code>reversed(list(zip(L, reversed(L))))</code> will return <code>[(3, 1), (2, 2), (1, 3)]</code>.</p></li><li><p><code>zip(zip(L, reversed(L)), reversed(list(zip(L, reversed(L)))))</code>: This part pairs the result of <code>zip(L, reversed(L))</code> with its reversed version. It takes corresponding elements from both sequences and forms pairs.<br>Example: If <code>zip(L, reversed(L))</code> is <code>[(1, 3), (2, 2), (3, 1)]</code> and its reverse is <code>[(3, 1), (2, 2), (1, 3)]</code>, then <code>zip(zip(L, reversed(L)), reversed(list(zip(L, reversed(L)))))</code> produces pairs of tuples like:</p><ul><li><code>((1, 3), (3, 1))</code></li><li><code>((2, 2), (2, 2))</code></li><li><code>((3, 1), (1, 3))</code></li></ul></li></ol><p>Finally, this expression is wrapped in <code>list()</code> to convert the zip object into a list of tuples.</p><h1 id="Exercise-6"><a href="#Exercise-6" class="headerlink" title="Exercise 6"></a>Exercise 6</h1><h3 id="Problem-Description-5"><a href="#Problem-Description-5" class="headerlink" title="Problem Description"></a>Problem Description</h3><p>Exercise 6 is similar to Exercise 5, requiring us to use <code>zip</code>, <code>*</code>, and <code>list</code> to solve the problem. We are given a variable number of arguments <code>*L</code>, and the goal is to output them in the form of <code>[(...), (...)]</code>. This task is simpler than the previous one, as the pairing only needs to reverse and mirror the elements.</p><p>At first, I attempted the following approach:</p><h3 id="Wrong-Solution-1"><a href="#Wrong-Solution-1" class="headerlink" title="Wrong Solution:"></a>Wrong Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">*L</span>):</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">list</span>(<span class="built_in">zip</span>(<span class="built_in">zip</span>(L, <span class="built_in">reversed</span>(L)), <span class="built_in">zip</span>(<span class="built_in">reversed</span>(L), L)))</span><br></pre></td></tr></table></figure><p>I tried using <code>zip</code> to pair elements in forward and reverse order:</p><p><code>zip(L, reversed(L))</code> pairs the elements of <code>L</code> with the reversed version of <code>L</code>, while <code>zip(reversed(L), L)</code> pairs them in the reverse order.</p><p>However, the output of this solution was:</p><p><code>[((0, 1), (1, 0)), ((1, 0), (0, 1))]</code></p><p>This did not meet the requirements, as the pairs <code>(0, 1)</code> and <code>(1, 0)</code> were grouped separately. The correct format should have <code>0, 1, 1, 0</code> in the same tuple.</p><h3 id="Correct-Solution-1"><a href="#Correct-Solution-1" class="headerlink" title="Correct Solution:"></a>Correct Solution:</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">*L</span>):</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">list</span>(<span class="built_in">zip</span>(*<span class="built_in">zip</span>(L, <span class="built_in">reversed</span>(L)), *<span class="built_in">zip</span>(<span class="built_in">reversed</span>(L), L)))</span><br></pre></td></tr></table></figure><h3 id="Explanation-of-the-Fix"><a href="#Explanation-of-the-Fix" class="headerlink" title="Explanation of the Fix:"></a>Explanation of the Fix:</h3><p>To achieve the desired output, we need to flatten or “unpack” the pairs created by <code>zip(L, reversed(L))</code> and <code>zip(reversed(L), L)</code> into individual elements and combine them correctly. This is where the <code>*</code> operator comes in, which unpacks the results from the <code>zip</code> function.</p><p>By using <code>*</code> before <code>zip(L, reversed(L))</code> and <code>zip(reversed(L), L)</code>, you effectively unpack the tuples into separate elements, allowing the outer <code>zip</code> function to combine them in the desired form.</p><ul><li><p><code>*zip(L, reversed(L))</code>: This unpacks the paired tuples from <code>L</code> and <code>reversed(L)</code>. Instead of getting pairs like <code>(0, 1)</code>, it unpacks them into <code>0, 1, 1, 0</code>.</p></li><li><p><code>*zip(reversed(L), L)</code>: Similarly, this unpacks the reversed pairs.</p></li></ul><p>The final <code>zip</code> call then combines these unpacked elements into the correct tuple format. The result is:</p><p><code>[(0, 1, 1, 0), (1, 0, 0, 1)]</code></p><p>This ensures that the mirrored pairs are placed together in the same tuple as required by the problem.</p>]]></content>
<summary type="html"><h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><h3 id="Problem-Description"><a href="#Pr</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="9021" scheme="https://longsizhuo.github.io/tags/9021/"/>
<category term="TUT" scheme="https://longsizhuo.github.io/tags/TUT/"/>
</entry>
<entry>
<title>DartsInter-Uni Programming Contest Tasks Leaderboard Contest</title>
<link href="https://longsizhuo.github.io/post/c61e596.html"/>
<id>https://longsizhuo.github.io/post/c61e596.html</id>
<published>2024-09-20T14:00:00.000Z</published>
<updated>2024-10-03T08:57:12.474Z</updated>
<content type="html"><![CDATA[<h1 id="Description:"><a href="#Description:" class="headerlink" title="Description:"></a>Description:</h1><p>Darts<br><a href="https://interunia.unswcpmsoc.com/task/Darts/">https://interunia.unswcpmsoc.com/task/Darts/</a></p><h1 id="Thinking:"><a href="#Thinking:" class="headerlink" title="Thinking:"></a>Thinking:</h1><p>This contest is harder than I imaged, this is the second task, and I spent a lot of time but when I checked the Leaderboard and no one has solved it yet, I feel a little bit better.<br>At first, I thought of simply judging whether this point is in the middle of this circle, using Euclidean distance calculation. But later I found that when there are n circles and m darts, the amount of data is surprisingly large. After the brute force cracking timed out, I had to consider a new method.</p><p>We can use the gridded <code>Spatial Indexing</code>, the specific steps are as follows:</p><h3 id="1-Spatial-division-Divide-the-entire-plane-into-grids-of-equal-size-Grid-and-map-the-target-and-dart-to-the-corresponding-grid"><a href="#1-Spatial-division-Divide-the-entire-plane-into-grids-of-equal-size-Grid-and-map-the-target-and-dart-to-the-corresponding-grid" class="headerlink" title="1. Spatial division: Divide the entire plane into grids of equal size (Grid), and map the target and dart to the corresponding grid."></a>1. Spatial division: Divide the entire plane into grids of equal size (Grid), and map the target and dart to the corresponding grid.</h3><p>Purpose:</p><ul><li>Reduce the number of targets that need to be calculated.</li><li>For each dart, you only need to check the targets in its grid and adjacent grids.</li></ul><h3 id="2-Map-Targets-to-Grids"><a href="#2-Map-Targets-to-Grids" class="headerlink" title="2. Map Targets to Grids:"></a>2. Map Targets to Grids:</h3><ul><li>Calculate the bounding box of each target.<ul><li>Lower-left corner: ( (x_i - r_i, y_i - r_i) )</li><li>Upper-right corner: ( (x_i + r_i, y_i + r_i) )</li></ul></li><li>Record all grid cells covered by this rectangle and add the target index to these grid cells.</li></ul><h3 id="3-Map-Darts-to-Grids"><a href="#3-Map-Darts-to-Grids" class="headerlink" title="3. Map Darts to Grids:"></a>3. Map Darts to Grids:</h3><p>For each dart, calculate the grid coordinates where it is located.</p><h3 id="4-Check-if-the-Dart-Hits-a-Target"><a href="#4-Check-if-the-Dart-Hits-a-Target" class="headerlink" title="4. Check if the Dart Hits a Target:"></a>4. Check if the Dart Hits a Target:</h3><ul><li>For each dart, check all targets in its grid and the adjacent 8 grids.</li><li>Calculate the distance from the dart to the center of each target and determine whether it is less than or equal to the square of the target’s radius, i.e., ( (dx - x_i)^2 + (dy - y_i)^2 \leq r_i^2 ).</li></ul><h2 id="Grid-Division-Parameters"><a href="#Grid-Division-Parameters" class="headerlink" title="Grid Division Parameters"></a>Grid Division Parameters</h2><p>Grid size (<code>GRID_SIZE</code>):</p><ul><li>Choose an appropriate grid size, such as 500.</li><li>The choice of grid size requires a trade-off between space and time efficiency.</li></ul><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">auto get_grid_cell = [&](long long x_n, long long y_n) {</span><br><span class="line"> <span class="built_in">int</span> gx = <span class="built_in">int</span>((x_n - min_x) / s);</span><br><span class="line"> <span class="built_in">int</span> gy = <span class="built_in">int</span>((y_n - min_y) / s);</span><br><span class="line"> <span class="keyword">return</span> make_pair(gx, gy);</span><br><span class="line">};</span><br></pre></td></tr></table></figure><p>Coordinate mapping function:</p><p>Maps actual coordinates to grid coordinates.</p><ul><li>s is the actual length of each grid cell.</li><li>$min_x$ and $min_y$ are the minimum values among all target and dart coordinates, used to shift the coordinates.</li></ul><h2 id="Mapping-Targets-to-Grids"><a href="#Mapping-Targets-to-Grids" class="headerlink" title="Mapping Targets to Grids"></a>Mapping Targets to Grids</h2><ul><li>Iterate over all targets and calculate their covered grid ranges.</li><li>In these grids, record the indices of the targets.</li></ul><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="built_in">int</span> idx = <span class="number">0</span>; idx < n; ++idx) {</span><br><span class="line"> <span class="built_in">int</span> x, y, r;</span><br><span class="line"> tie(x, y, r) = circles[idx];</span><br><span class="line"> long long x_min = x - r;</span><br><span class="line"> long long x_max = x + r;</span><br><span class="line"> long long y_min = y - r;</span><br><span class="line"> long long y_max = y + r;</span><br><span class="line"> auto [gx_min, gy_min] = get_grid_cell(x_min, y_min);</span><br><span class="line"> auto [gx_max, gy_max] = get_grid_cell(x_max, y_max);</span><br><span class="line"> <span class="keyword">for</span> (<span class="built_in">int</span> gx = gx_min; gx <= gx_max; ++gx) {</span><br><span class="line"> <span class="keyword">for</span> (<span class="built_in">int</span> gy = gy_min; gy <= gy_max; ++gy) {</span><br><span class="line"> long long key = get_grid_key(gx, gy);</span><br><span class="line"> grid[key].push_back(idx); // 存储靶子索引</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h2 id="Mapping-Darts-to-Grids"><a href="#Mapping-Darts-to-Grids" class="headerlink" title="Mapping Darts to Grids"></a>Mapping Darts to Grids</h2><ul><li>For each dart, calculate the grid cell it belongs to.</li><li>No need to store darts in grids; we process them directly.</li></ul><h2 id="Checking-if-Darts-Hit-Targets"><a href="#Checking-if-Darts-Hit-Targets" class="headerlink" title="Checking if Darts Hit Targets"></a>Checking if Darts Hit Targets</h2><ul><li>For each dart, get its grid coordinates ( (gx, gy) ).</li><li>Check the dart’s grid cell and its 8 adjacent grid cells.</li><li>For each target in these grids, calculate the distance to the dart.</li><li>If the distance squared is less than or equal to the target’s radius squared, increment the counter.</li></ul><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (const auto& p : points) {</span><br><span class="line"> <span class="built_in">int</span> dx = p.first;</span><br><span class="line"> <span class="built_in">int</span> dy = p.second;</span><br><span class="line"> auto [gx, gy] = get_grid_cell(dx, dy);</span><br><span class="line"> <span class="built_in">bool</span> found = false;</span><br><span class="line"> </span><br><span class="line"> // Check the grid <span class="keyword">and</span> the <span class="number">8</span> adjacent grids</span><br><span class="line"> <span class="keyword">for</span> (<span class="built_in">int</span> ix = gx - <span class="number">1</span>; ix <= gx + <span class="number">1</span>; ++ix) {</span><br><span class="line"> <span class="keyword">for</span> (<span class="built_in">int</span> iy = gy - <span class="number">1</span>; iy <= gy + <span class="number">1</span>; ++iy) {</span><br><span class="line"> long long key = get_grid_key(ix, iy);</span><br><span class="line"> <span class="keyword">if</span> (grid.count(key)) {</span><br><span class="line"> const auto& circle_indices = grid[key];</span><br><span class="line"> <span class="keyword">for</span> (<span class="built_in">int</span> idx : circle_indices) {</span><br><span class="line"> <span class="built_in">int</span> x, y, r;</span><br><span class="line"> tie(x, y, r) = circles[idx];</span><br><span class="line"> // caculate the distance</span><br><span class="line"> long long dx_sq = (long long)(dx - x) * (dx - x);</span><br><span class="line"> long long dy_sq = (long long)(dy - y) * (dy - y);</span><br><span class="line"> long long r_sq = (long long)r * r;</span><br><span class="line"> <span class="keyword">if</span> (dx_sq + dy_sq <= r_sq) {</span><br><span class="line"> ans++;</span><br><span class="line"> found = true;</span><br><span class="line"> <span class="keyword">break</span>; // The dart has found the target, check the <span class="built_in">next</span> dart</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (found) <span class="keyword">break</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (found) <span class="keyword">break</span>;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><h1 id="code"><a href="#code" class="headerlink" title="code:"></a>code:</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> math</span><br><span class="line"></span><br><span class="line">n, m = <span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split())</span><br><span class="line"></span><br><span class="line">circles = []</span><br><span class="line"></span><br><span class="line">min_x = min_y = <span class="built_in">float</span>(<span class="string">'inf'</span>)</span><br><span class="line">max_x = max_y = <span class="built_in">float</span>(<span class="string">'-inf'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line"> x, y, r = <span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split())</span><br><span class="line"> circles.append((x, y, r))</span><br><span class="line"> min_x = <span class="built_in">min</span>(min_x, x - r)</span><br><span class="line"> max_x = <span class="built_in">max</span>(max_x, x + r)</span><br><span class="line"> min_y = <span class="built_in">min</span>(min_y, y - r)</span><br><span class="line"> max_y = <span class="built_in">max</span>(max_y, y + r)</span><br><span class="line"></span><br><span class="line">points = []</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(m):</span><br><span class="line"> dx, dy = <span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split())</span><br><span class="line"> points.append((dx, dy))</span><br><span class="line"> min_x = <span class="built_in">min</span>(min_x, dx)</span><br><span class="line"> max_x = <span class="built_in">max</span>(max_x, dx)</span><br><span class="line"> min_y = <span class="built_in">min</span>(min_y, dy)</span><br><span class="line"> max_y = <span class="built_in">max</span>(max_y, dy)</span><br><span class="line"></span><br><span class="line">GRID_SIZE = <span class="number">500</span></span><br><span class="line">delta_x = max_x - min_x</span><br><span class="line">delta_y = max_y - min_y</span><br><span class="line">s = <span class="built_in">max</span>(delta_x, delta_y) / GRID_SIZE</span><br><span class="line"><span class="keyword">if</span> s == <span class="number">0</span>:</span><br><span class="line"> s = <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Function that maps coordinates to grid indices</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">get_grid_cell</span>(<span class="params">x_n, y_n</span>):</span><br><span class="line"> gx = <span class="built_in">int</span>((x_n - min_x) / s)</span><br><span class="line"> gy = <span class="built_in">int</span>((y_n - min_y) / s)</span><br><span class="line"> <span class="keyword">return</span> gx, gy</span><br><span class="line"></span><br><span class="line">grid = {}</span><br><span class="line"></span><br><span class="line"><span class="comment"># Mapping the targets onto the grid</span></span><br><span class="line"><span class="keyword">for</span> idx, (x, y, r) <span class="keyword">in</span> <span class="built_in">enumerate</span>(circles):</span><br><span class="line"> x_min = x - r</span><br><span class="line"> x_max = x + r</span><br><span class="line"> y_min = y - r</span><br><span class="line"> y_max = y + r</span><br><span class="line"> gx_min, gy_min = get_grid_cell(x_min, y_min)</span><br><span class="line"> gx_max, gy_max = get_grid_cell(x_max, y_max)</span><br><span class="line"> <span class="keyword">for</span> gx <span class="keyword">in</span> <span class="built_in">range</span>(gx_min, gx_max + <span class="number">1</span>):</span><br><span class="line"> <span class="keyword">for</span> gy <span class="keyword">in</span> <span class="built_in">range</span>(gy_min, gy_max + <span class="number">1</span>):</span><br><span class="line"> <span class="keyword">if</span> (gx, gy) <span class="keyword">not</span> <span class="keyword">in</span> grid:</span><br><span class="line"> grid[(gx, gy)] = []</span><br><span class="line"> grid[(gx, gy)].append(idx) <span class="comment"># store the target index</span></span><br><span class="line"></span><br><span class="line">ans = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># For each dart, check the target in the grid where it is located</span></span><br><span class="line"><span class="keyword">for</span> dx, dy <span class="keyword">in</span> points:</span><br><span class="line"> gx, gy = get_grid_cell(dx, dy)</span><br><span class="line"> found = <span class="literal">False</span></span><br><span class="line"> <span class="keyword">if</span> (gx, gy) <span class="keyword">in</span> grid:</span><br><span class="line"> <span class="keyword">for</span> idx <span class="keyword">in</span> grid[(gx, gy)]:</span><br><span class="line"> x, y, r = circles[idx]</span><br><span class="line"> <span class="comment"># Determine if the dart is in the target</span></span><br><span class="line"> <span class="keyword">if</span> (dx - x) ** <span class="number">2</span> + (dy - y) ** <span class="number">2</span> <= r ** <span class="number">2</span>:</span><br><span class="line"> ans += <span class="number">1</span></span><br><span class="line"> found = <span class="literal">True</span></span><br><span class="line"> <span class="keyword">break</span> <span class="comment"># 找到后跳出循环</span></span><br><span class="line"> <span class="comment"># The grids do not overlap and the surrounding grids are not detected?</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(ans)</span><br></pre></td></tr></table></figure><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><iostream></span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><vector></span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><cmath></span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><unordered_map></span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><algorithm></span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><climits></span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>{</span><br><span class="line"> <span class="comment">// Fast input/output</span></span><br><span class="line"> ios::<span class="built_in">sync_with_stdio</span>(<span class="literal">false</span>);</span><br><span class="line"> cin.<span class="built_in">tie</span>(<span class="literal">NULL</span>);</span><br><span class="line"></span><br><span class="line"> <span class="type">int</span> n, m;</span><br><span class="line"> cin >> n >> m;</span><br><span class="line"></span><br><span class="line"> vector<tuple<<span class="type">int</span>, <span class="type">int</span>, <span class="type">int</span>>> circles;</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> min_x = LLONG_MAX, min_y = LLONG_MAX;</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> max_x = LLONG_MIN, max_y = LLONG_MIN;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Read circles and update bounding box</span></span><br><span class="line"> <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i < n; ++i) {</span><br><span class="line"> <span class="type">int</span> x, y, r;</span><br><span class="line"> cin >> x >> y >> r;</span><br><span class="line"> circles.<span class="built_in">emplace_back</span>(x, y, r);</span><br><span class="line"> min_x = <span class="built_in">min</span>(min_x, (<span class="type">long</span> <span class="type">long</span>)x - r);</span><br><span class="line"> max_x = <span class="built_in">max</span>(max_x, (<span class="type">long</span> <span class="type">long</span>)x + r);</span><br><span class="line"> min_y = <span class="built_in">min</span>(min_y, (<span class="type">long</span> <span class="type">long</span>)y - r);</span><br><span class="line"> max_y = <span class="built_in">max</span>(max_y, (<span class="type">long</span> <span class="type">long</span>)y + r);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> vector<pair<<span class="type">int</span>, <span class="type">int</span>>> points;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Read darts and update bounding box</span></span><br><span class="line"> <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i < m; ++i) {</span><br><span class="line"> <span class="type">int</span> dx, dy;</span><br><span class="line"> cin >> dx >> dy;</span><br><span class="line"> points.<span class="built_in">emplace_back</span>(dx, dy);</span><br><span class="line"> min_x = <span class="built_in">min</span>(min_x, (<span class="type">long</span> <span class="type">long</span>)dx);</span><br><span class="line"> max_x = <span class="built_in">max</span>(max_x, (<span class="type">long</span> <span class="type">long</span>)dx);</span><br><span class="line"> min_y = <span class="built_in">min</span>(min_y, (<span class="type">long</span> <span class="type">long</span>)dy);</span><br><span class="line"> max_y = <span class="built_in">max</span>(max_y, (<span class="type">long</span> <span class="type">long</span>)dy);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="type">const</span> <span class="type">int</span> GRID_SIZE = <span class="number">500</span>;</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> delta_x = max_x - min_x;</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> delta_y = max_y - min_y;</span><br><span class="line"> <span class="type">double</span> s = <span class="built_in">max</span>(delta_x, delta_y) / (<span class="type">double</span>)GRID_SIZE;</span><br><span class="line"> <span class="keyword">if</span> (s == <span class="number">0</span>) {</span><br><span class="line"> s = <span class="number">1</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Function to get grid cell indices</span></span><br><span class="line"> <span class="keyword">auto</span> get_grid_cell = [&](<span class="type">long</span> <span class="type">long</span> x_n, <span class="type">long</span> <span class="type">long</span> y_n) {</span><br><span class="line"> <span class="type">int</span> gx = <span class="built_in">int</span>((x_n - min_x) / s);</span><br><span class="line"> <span class="type">int</span> gy = <span class="built_in">int</span>((y_n - min_y) / s);</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">make_pair</span>(gx, gy);</span><br><span class="line"> };</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Function to combine gx and gy into a single key</span></span><br><span class="line"> <span class="keyword">auto</span> get_grid_key = [](<span class="type">int</span> gx, <span class="type">int</span> gy) -> <span class="type">long</span> <span class="type">long</span> {</span><br><span class="line"> <span class="built_in">return</span> ((<span class="type">long</span> <span class="type">long</span>)gx << <span class="number">32</span>) | (<span class="type">unsigned</span> <span class="type">int</span>)gy;</span><br><span class="line"> };</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Map from grid cell key to list of circle indices</span></span><br><span class="line"> unordered_map<<span class="type">long</span> <span class="type">long</span>, vector<<span class="type">int</span>>> grid;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Map circles to grid cells</span></span><br><span class="line"> <span class="keyword">for</span> (<span class="type">int</span> idx = <span class="number">0</span>; idx < n; ++idx) {</span><br><span class="line"> <span class="type">int</span> x, y, r;</span><br><span class="line"> <span class="built_in">tie</span>(x, y, r) = circles[idx];</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> x_min = x - r;</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> x_max = x + r;</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> y_min = y - r;</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> y_max = y + r;</span><br><span class="line"> <span class="keyword">auto</span> [gx_min, gy_min] = <span class="built_in">get_grid_cell</span>(x_min, y_min);</span><br><span class="line"> <span class="keyword">auto</span> [gx_max, gy_max] = <span class="built_in">get_grid_cell</span>(x_max, y_max);</span><br><span class="line"> <span class="keyword">for</span> (<span class="type">int</span> gx = gx_min; gx <= gx_max; ++gx) {</span><br><span class="line"> <span class="keyword">for</span> (<span class="type">int</span> gy = gy_min; gy <= gy_max; ++gy) {</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> key = <span class="built_in">get_grid_key</span>(gx, gy);</span><br><span class="line"> grid[key].<span class="built_in">push_back</span>(idx); <span class="comment">// Store circle index</span></span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="type">int</span> ans = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// For each dart, check circles in its grid cell and adjacent cells</span></span><br><span class="line"> <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span>& p : points) {</span><br><span class="line"> <span class="type">int</span> dx = p.first;</span><br><span class="line"> <span class="type">int</span> dy = p.second;</span><br><span class="line"> <span class="keyword">auto</span> [gx, gy] = <span class="built_in">get_grid_cell</span>(dx, dy);</span><br><span class="line"> <span class="type">bool</span> found = <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Check the dart's grid cell and its 8 neighbors</span></span><br><span class="line"> <span class="keyword">for</span> (<span class="type">int</span> ix = gx - <span class="number">1</span>; ix <= gx + <span class="number">1</span>; ++ix) {</span><br><span class="line"> <span class="keyword">for</span> (<span class="type">int</span> iy = gy - <span class="number">1</span>; iy <= gy + <span class="number">1</span>; ++iy) {</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> key = <span class="built_in">get_grid_key</span>(ix, iy);</span><br><span class="line"> <span class="keyword">if</span> (grid.<span class="built_in">count</span>(key)) {</span><br><span class="line"> <span class="type">const</span> <span class="keyword">auto</span>& circle_indices = grid[key];</span><br><span class="line"> <span class="keyword">for</span> (<span class="type">int</span> idx : circle_indices) {</span><br><span class="line"> <span class="type">int</span> x, y, r;</span><br><span class="line"> <span class="built_in">tie</span>(x, y, r) = circles[idx];</span><br><span class="line"> <span class="comment">// Check if the dart is inside the circle</span></span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> dx_sq = (<span class="type">long</span> <span class="type">long</span>)(dx - x) * (dx - x);</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> dy_sq = (<span class="type">long</span> <span class="type">long</span>)(dy - y) * (dy - y);</span><br><span class="line"> <span class="type">long</span> <span class="type">long</span> r_sq = (<span class="type">long</span> <span class="type">long</span>)r * r;</span><br><span class="line"> <span class="keyword">if</span> (dx_sq + dy_sq <= r_sq) {</span><br><span class="line"> ans++;</span><br><span class="line"> found = <span class="literal">true</span>;</span><br><span class="line"> <span class="keyword">break</span>; <span class="comment">// Move to next dart</span></span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (found) <span class="keyword">break</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (found) <span class="keyword">break</span>;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> cout << ans << <span class="string">'\n'</span>;</span><br><span class="line"> <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">}</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="Description:"><a href="#Description:" class="headerlink" title="Description:"></a>Description:</h1><p>Darts<br><a href="https://inte</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="C++" scheme="https://longsizhuo.github.io/tags/C/"/>
<category term="Contest" scheme="https://longsizhuo.github.io/tags/Contest/"/>
<category term="Inter-Uni Programming Contest" scheme="https://longsizhuo.github.io/tags/Inter-Uni-Programming-Contest/"/>
</entry>
<entry>
<title>9021_TUT_1</title>
<link href="https://longsizhuo.github.io/post/ac786f6f.html"/>
<id>https://longsizhuo.github.io/post/ac786f6f.html</id>
<published>2024-09-10T14:00:00.000Z</published>
<updated>2024-09-17T18:16:47.252Z</updated>
<content type="html"><![CDATA[<h1 id="Slide-1-Introduction"><a href="#Slide-1-Introduction" class="headerlink" title="Slide 1: Introduction"></a>Slide 1: Introduction</h1><p>Today, we are going to walk through six Python functions that perform various tasks involving integers, lists, and text files. Each function demonstrates different ways to manipulate data, including string formatting, list processing, and reading from files.</p><h1 id="Slide-2-Function-1-f1-m-n"><a href="#Slide-2-Function-1-f1-m-n" class="headerlink" title="Slide 2: Function 1 - f1(m, n)"></a>Slide 2: Function 1 - f1(m, n)</h1><p>The first function, f1, generates a simple string pattern. Here’s how it works:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">m, n</span>):</span><br><span class="line"> <span class="keyword">return</span> (<span class="string">'|'</span> + <span class="string">'_'</span> * n + <span class="string">'|'</span>) * m</span><br></pre></td></tr></table></figure><ol><li>The function takes two integer arguments, m and n. Both are assumed to be at least 0.</li><li>It constructs a pattern consisting of vertical bars (|) enclosing underscores (_), repeated m times. The number of underscores between the bars is determined by n.</li><li>For example, if m = 3 and n = 4, the output would be:<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">|____||____||____|</span><br></pre></td></tr></table></figure></li></ol><h1 id="Slide-3-Function-2-f2-n"><a href="#Slide-3-Function-2-f2-n" class="headerlink" title="Slide 3: Function 2 - f2(n)"></a>Slide 3: Function 2 - f2(n)</h1><p>The second function, f2, creates a square pattern made up of digits. Here’s the function:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">n</span>):</span><br><span class="line"> <span class="keyword">return</span> (<span class="built_in">str</span>(n) * n + <span class="string">'\n'</span>) * n</span><br></pre></td></tr></table></figure><ol><li>This function takes an integer n and generates a square of n rows, where each row contains the digit n repeated n times.</li><li>The pattern ends with a newline after each row.</li><li>For example, if n = 3, the output will be:<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">333</span></span><br><span class="line"><span class="number">333</span></span><br><span class="line"><span class="number">333</span></span><br></pre></td></tr></table></figure></li></ol><h1 id="Slide-4-Function-3-f3-L"><a href="#Slide-4-Function-3-f3-L" class="headerlink" title="Slide 4: Function 3 - f3(L)"></a>Slide 4: Function 3 - f3(L)</h1><p>Next, we have f3, which works on a list of integers:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f3</span>(<span class="params">L</span>):</span><br><span class="line"> <span class="keyword">while</span> <span class="built_in">len</span>(L) > <span class="number">1</span> <span class="keyword">and</span> L[<span class="number">0</span>] > L[<span class="number">1</span>]:</span><br><span class="line"> L.remove(L[<span class="number">0</span>])</span><br><span class="line"> <span class="built_in">print</span>(L)</span><br></pre></td></tr></table></figure><ol><li>This function removes elements from the start of the list until the first two consecutive elements are in non-decreasing order.</li><li>The process continues as long as the first element is strictly greater than the second element.</li><li>Once the list is stable, it prints the modified list.</li><li>For example, if L = [9, 8, 7, 10], the function will remove 9, 8, and 7, leaving [10].</li></ol><h1 id="Slide-5-Function-4-f4-D-n"><a href="#Slide-5-Function-4-f4-D-n" class="headerlink" title="Slide 5: Function 4 - f4(D, n)"></a>Slide 5: Function 4 - f4(D, n)</h1><p>The fourth function, f4, works with dictionaries:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f4</span>(<span class="params">D, n</span>):</span><br><span class="line"> <span class="keyword">if</span> n <span class="keyword">not</span> <span class="keyword">in</span> D:</span><br><span class="line"> <span class="keyword">return</span> []</span><br><span class="line"> ans = [n]</span><br><span class="line"> <span class="keyword">while</span> n <span class="keyword">in</span> D <span class="keyword">and</span> D[n] > n:</span><br><span class="line"> ans.append(D[n])</span><br><span class="line"> n = D[n]</span><br><span class="line"> <span class="keyword">return</span> ans</span><br></pre></td></tr></table></figure><ol><li>This function takes a dictionary D and an integer n. It generates a strictly increasing sequence of integers based on the relationships defined in the dictionary.</li><li>Starting from n, it appends D[n], D[D[n]], and so on to the list, as long as each subsequent value is greater than the previous one.</li><li>For example, if D = {1: 2, 2: 3, 3: 5} and n = 1, the function will return [1, 2, 3, 5].</li></ol><h1 id="Slide-6-Function-5-f5-filename"><a href="#Slide-6-Function-5-f5-filename" class="headerlink" title="Slide 6: Function 5 - f5(filename)"></a>Slide 6: Function 5 - f5(filename)</h1><p>The fifth function, f5, reads from a file and processes each line:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f5</span>(<span class="params">filename</span>):</span><br><span class="line"> <span class="keyword">with</span> <span class="built_in">open</span>(filename) <span class="keyword">as</span> f:</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> f:</span><br><span class="line"> name, number = i.split(<span class="string">','</span>)</span><br><span class="line"> number = <span class="built_in">int</span>(number) * <span class="number">1000</span></span><br><span class="line"> <span class="built_in">print</span>(<span class="string">f"<span class="subst">{number}</span> people named <span class="subst">{name}</span>"</span>)</span><br></pre></td></tr></table></figure><ol><li>This function reads a text file, where each line consists of a name and a count separated by a comma.</li><li>The function multiplies the count by 1000 and prints the result in the format: “X people named Y”.</li><li>For example, if the file contains a line “John,5”, it will print:<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">5000 people named John</span><br></pre></td></tr></table></figure></li></ol><h1 id="Slide-7-Function-6-f6-filename"><a href="#Slide-7-Function-6-f6-filename" class="headerlink" title="Slide 7: Function 6 - f6(filename)"></a>Slide 7: Function 6 - f6(filename)</h1><p>The final function, f6, also reads from a text file, but with a different format:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f6</span>(<span class="params">filename</span>):</span><br><span class="line"> <span class="keyword">with</span> <span class="built_in">open</span>(filename) <span class="keyword">as</span> f:</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> f:</span><br><span class="line"> <span class="keyword">if</span> <span class="keyword">not</span> i.isspace():</span><br><span class="line"> number, charactor = i.split()</span><br><span class="line"> <span class="built_in">print</span>(<span class="built_in">int</span>(number) * charactor)</span><br></pre></td></tr></table></figure><ol><li>This function reads lines that contain an integer followed by a symbol (e.g., “5 *”).</li><li>It multiplies the symbol by the integer and prints the result.</li><li>For example, if the file contains the line “3 # “, the function will print:<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">### </span><br></pre></td></tr></table></figure></li></ol>]]></content>
<summary type="html"><h1 id="Slide-1-Introduction"><a href="#Slide-1-Introduction" class="headerlink" title="Slide 1: Introduction"></a>Slide 1: Introduction</h1</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="Tutorial" scheme="https://longsizhuo.github.io/tags/Tutorial/"/>
</entry>
<entry>
<title>Top of an article</title>
<link href="https://longsizhuo.github.io/post/edc2b94.html"/>
<id>https://longsizhuo.github.io/post/edc2b94.html</id>
<published>2024-08-07T08:47:55.993Z</published>
<updated>2024-08-07T12:18:49.611Z</updated>
<content type="html"><![CDATA[<h1 id="longsizhuo123-github-io"><a href="#longsizhuo123-github-io" class="headerlink" title="longsizhuo123.github.io"></a>longsizhuo123.github.io</h1><p><img src="https://user-images.githubusercontent.com/114939201/214082770-35d1fb45-9891-4b73-ba89-18e33030640f.png" alt="pattern_stripes-1_1_2_0-0_125_1__cc2a35_4f372d_00a1b0_edc951_eb6941"></p><p><em>“Maybe it could be a nice memory”</em></p><p>Welcome to my personal blog repository on Github! My name is Sizhuo Long, and I am currently a student in Australia. This repository is home to my personal blog, which is built using the HEXO static site generator. </p><p>On my blog, you’ll find a variety of content including my thoughts on technology, programming, and the latest developments in my field of study. I also share my experiences and lessons learned from the projects I’ve worked on. </p><p>I hope that by sharing my knowledge and insights, I can help others who are interested in the same topics. I welcome any comments and feedback, and I am always open to collaboration. </p><p><strong>Thank you for visiting my blog</strong>, I hope you will find something interesting here. And I would really appreciate it if you could pay more attention to my blog and <strong>follow me</strong>.</p><h3 id="Why-you-should-follow-me"><a href="#Why-you-should-follow-me" class="headerlink" title="Why you should follow me"></a>Why you should follow me</h3><ul><li>I’ll share my personal experiences and thoughts on technology and programming </li><li>I’ll keep you updated on the latest developments in my field of study</li><li>I’m open to collaboration and feedback.</li></ul><h3 id="How-to-contact-me"><a href="#How-to-contact-me" class="headerlink" title="How to contact me"></a>How to contact me</h3><ul><li>Email: <a href="mailto:longsizhuo@gmail.com">longsizhuo@gmail.com</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/longsizhuo/">Sizhuo Long</a></li><li>XiaoHongShu(Small RedBook): <a href="https://www.xiaohongshu.com/user/profile/5c0b8cc2000000000601e809">@sizhuo_long</a></li></ul><p>Thank you for reading, and I hope you enjoy my blog!</p><p><img src="https://user-images.githubusercontent.com/114939201/214082782-ae84027e-0a15-4ed4-843b-00a29ea19480.png" alt="pattern_stripes-1_1_2_0-0_125_1__cc2a35_4f372d_00a1b0_edc951_eb6941"></p><p><strong><a href="https://longsizhuo.shinyapps.io/long/">Single -cellRNAData analysis tool</a></strong><br>The project I did before,There are many errors,Don’t spray。<br><strong><a href="../html/home.html">Shu Di Travel Bacteria</a></strong><br>This is a small assignment when I was a second junior year,It’s a group operation。At first I couldn’t get the link<code>html</code>document,I read a lot of official documents orCSDNdocument<br> 。Finally read an article,Said to beHEXODang the<code>generate</code>when,I willsource中的documentappendarrivepublicMiddle,I tried many times later,Discover directly<br>public为源document夹,Just call the directory。Although this will cause it to be unable to bemddocument中超链接arrivedocument。 </p><p>at the same time,也exist新的bugunsolved:login.htmlUnable toindex.htmlJump<br>Linkin:</p><div class="badge-base LI-profile-badge" data-locale="zh_CN" data-size="medium" data-theme="dark" data-type="HORIZONTAL" data-vanity="longsizhuo" data-version="v1"><a class="badge-base__link LI-simple-link" href="https://au.linkedin.com/in/longsizhuo?trk=profile-badge">Sizhuo Long</a></div>]]></content>
<summary type="html"><h1 id="longsizhuo123-github-io"><a href="#longsizhuo123-github-io" class="headerlink" title="longsizhuo123.github.io"></a>longsizhuo123.git</summary>
<category term="front end" scheme="https://longsizhuo.github.io/categories/front-end/"/>
<category term="HEXO" scheme="https://longsizhuo.github.io/categories/front-end/HEXO/"/>
<category term="unsolved" scheme="https://longsizhuo.github.io/categories/unsolved/"/>
<category term="existbug" scheme="https://longsizhuo.github.io/categories/unsolved/existbug/"/>
<category term="unsolved" scheme="https://longsizhuo.github.io/tags/unsolved/"/>
<category term="front end" scheme="https://longsizhuo.github.io/tags/front-end/"/>
</entry>
<entry>
<title>964E</title>
<link href="https://longsizhuo.github.io/post/2280b647.html"/>
<id>https://longsizhuo.github.io/post/2280b647.html</id>
<published>2024-08-06T17:34:00.000Z</published>
<updated>2024-08-07T09:57:45.055Z</updated>
<content type="html"><![CDATA[<h1 id="Question"><a href="#Question" class="headerlink" title="Question:"></a>Question:</h1><div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Triple Operations</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 megabytes</div><div class="input-file input-standard"><div class="property-title">input</div>standard input</div><div class="output-file output-standard"><div class="property-title">output</div>standard output</div></div><div><p>On the board Ivy wrote down all integers from <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-1-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>l</mi></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-1" style="width: 0.36em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.301em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.313em, 1000.24em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-2"><span class="mi" id="MathJax-Span-3" style="font-family: MathJax_Math-italic;">l</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 1.004em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>l</mi></math></span></span><script type="math/tex" id="MathJax-Element-1">l</script> to <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-2-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>r</mi></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-4" style="width: 0.598em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.61em, 1000.48em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-5"><span class="mi" id="MathJax-Span-6" style="font-family: MathJax_Math-italic;">r</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 0.718em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>r</mi></math></span></span><script type="math/tex" id="MathJax-Element-2">r</script>, inclusive.</p><p>In an operation, she does the following: </p><ul> <li> pick two numbers <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-3-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-7" style="width: 0.717em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.598em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.61em, 1000.54em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-8"><span class="mi" id="MathJax-Span-9" style="font-family: MathJax_Math-italic;">x</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 0.718em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math></span></span><script type="math/tex" id="MathJax-Element-3">x</script> and <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-4-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>y</mi></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-10" style="width: 0.598em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.61em, 1000.48em, 2.562em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-11"><span class="mi" id="MathJax-Span-12" style="font-family: MathJax_Math-italic;">y<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.003em;"></span></span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.282em; border-left: 0px solid; width: 0px; height: 0.932em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>y</mi></math></span></span><script type="math/tex" id="MathJax-Element-4">y</script> on the board, erase them, and in their place write the numbers <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-5-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>3</mn><mi>x</mi></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-13" style="width: 1.313em; display: inline-block;"><span style="display: inline-block; position: relative; width: 1.074em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.372em, 1001.01em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-14"><span class="mn" id="MathJax-Span-15" style="font-family: MathJax_Main;">3</span><span class="mi" id="MathJax-Span-16" style="font-family: MathJax_Math-italic;">x</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 1.004em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mn>3</mn><mi>x</mi></math></span></span><script type="math/tex" id="MathJax-Element-5">3x</script> and <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-6-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mo fence="false" stretchy="false">&#x230A;</mo><mfrac><mi>y</mi><mn>3</mn></mfrac><mo fence="false" stretchy="false">&#x230B;</mo></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-17" style="width: 1.967em; display: inline-block;"><span style="display: inline-block; position: relative; width: 1.61em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.134em, 1001.43em, 2.801em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-18"><span class="mo" id="MathJax-Span-19" style="font-family: MathJax_Main;">⌊</span><span class="mfrac" id="MathJax-Span-20"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px; margin-right: 0.122em; margin-left: 0.122em;"><span style="position: absolute; clip: rect(3.515em, 1000.36em, 4.289em, -999.997em); top: -4.58em; left: 50%; margin-left: -0.176em;"><span class="mi" id="MathJax-Span-21" style="font-size: 70.7%; font-family: MathJax_Math-italic;">y<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.003em;"></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.336em, 1000.3em, 4.17em, -999.997em); top: -3.568em; left: 50%; margin-left: -0.176em;"><span class="mn" id="MathJax-Span-22" style="font-size: 70.7%; font-family: MathJax_Main;">3</span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(0.836em, 1000.48em, 1.253em, -999.997em); top: -1.307em; left: 0em;"><span style="display: inline-block; overflow: hidden; vertical-align: 0em; border-top: 1.3px solid; width: 0.479em; height: 0px;"></span><span style="display: inline-block; width: 0px; height: 1.074em;"></span></span></span></span><span class="mo" id="MathJax-Span-23" style="font-family: MathJax_Main;">⌋</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.568em; border-left: 0px solid; width: 0px; height: 1.718em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mo fence="false" stretchy="false">⌊</mo><mfrac><mi>y</mi><mn>3</mn></mfrac><mo fence="false" stretchy="false">⌋</mo></math></span></span><script type="math/tex" id="MathJax-Element-6">\lfloor \frac{y}{3} \rfloor</script>. (Here <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-7-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mo fence="false" stretchy="false">&#x230A;</mo><mo>&#x2219;</mo><mo fence="false" stretchy="false">&#x230B;</mo></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-24" style="width: 1.67em; display: inline-block;"><span style="display: inline-block; position: relative; width: 1.372em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.253em, 1001.19em, 2.622em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-25"><span class="mo" id="MathJax-Span-26" style="font-family: MathJax_Main;">⌊</span><span class="mo" id="MathJax-Span-27" style="font-family: MathJax_Main;">∙</span><span class="mo" id="MathJax-Span-28" style="font-family: MathJax_Main;">⌋</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.354em; border-left: 0px solid; width: 0px; height: 1.361em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mo fence="false" stretchy="false">⌊</mo><mo>∙</mo><mo fence="false" stretchy="false">⌋</mo></math></span></span><script type="math/tex" id="MathJax-Element-7">\lfloor \bullet \rfloor</script> denotes rounding down to the nearest integer).</li></ul> <p>What is the minimum number of operations Ivy needs to make all numbers on the board equal <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-8-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>0</mn></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-29" style="width: 0.598em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.372em, 1000.42em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-30"><span class="mn" id="MathJax-Span-31" style="font-family: MathJax_Main;">0</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 1.004em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mn>0</mn></math></span></span><script type="math/tex" id="MathJax-Element-8">0</script>? We have a proof that this is always possible.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains an integer <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-9-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>t</mi></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-32" style="width: 0.479em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.36em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.372em, 1000.3em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-33"><span class="mi" id="MathJax-Span-34" style="font-family: MathJax_Math-italic;">t</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 0.932em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>t</mi></math></span></span><script type="math/tex" id="MathJax-Element-9">t</script> (<span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-10-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>&#x2264;</mo><mi>t</mi><mo>&#x2264;</mo><msup><mn>10</mn><mn>4</mn></msup></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-35" style="width: 6.074em; display: inline-block;"><span style="display: inline-block; position: relative; width: 5.063em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.134em, 1005.06em, 2.503em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-36"><span class="mn" id="MathJax-Span-37" style="font-family: MathJax_Main;">1</span><span class="mo" id="MathJax-Span-38" style="font-family: MathJax_Main; padding-left: 0.301em;">≤</span><span class="mi" id="MathJax-Span-39" style="font-family: MathJax_Math-italic; padding-left: 0.301em;">t</span><span class="mo" id="MathJax-Span-40" style="font-family: MathJax_Main; padding-left: 0.301em;">≤</span><span class="msubsup" id="MathJax-Span-41" style="padding-left: 0.301em;"><span style="display: inline-block; position: relative; width: 1.432em; height: 0px;"><span style="position: absolute; clip: rect(3.158em, 1000.96em, 4.17em, -999.997em); top: -3.985em; left: 0em;"><span class="mn" id="MathJax-Span-42" style="font-family: MathJax_Main;">10</span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; top: -4.402em; left: 1.015em;"><span class="mn" id="MathJax-Span-43" style="font-size: 70.7%; font-family: MathJax_Main;">4</span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.211em; border-left: 0px solid; width: 0px; height: 1.361em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>≤</mo><mi>t</mi><mo>≤</mo><msup><mn>10</mn><mn>4</mn></msup></math></span></span><script type="math/tex" id="MathJax-Element-10">1 \leq t \leq 10^4</script>) — the number of test cases.</p><p>The only line of each test case contains two integers <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-11-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>l</mi></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-44" style="width: 0.36em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.301em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.313em, 1000.24em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-45"><span class="mi" id="MathJax-Span-46" style="font-family: MathJax_Math-italic;">l</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 1.004em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>l</mi></math></span></span><script type="math/tex" id="MathJax-Element-11">l</script> and <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-12-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>r</mi></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-47" style="width: 0.598em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.61em, 1000.48em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-48"><span class="mi" id="MathJax-Span-49" style="font-family: MathJax_Math-italic;">r</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 0.718em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>r</mi></math></span></span><script type="math/tex" id="MathJax-Element-12">r</script> (<span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-13-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>&#x2264;</mo><mi>l</mi><mo>&lt;</mo><mi>r</mi><mo>&#x2264;</mo><mn>2</mn><mo>&#x22C5;</mo><msup><mn>10</mn><mn>5</mn></msup></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-50" style="width: 9.765em; display: inline-block;"><span style="display: inline-block; position: relative; width: 8.098em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.134em, 1008.1em, 2.503em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-51"><span class="mn" id="MathJax-Span-52" style="font-family: MathJax_Main;">1</span><span class="mo" id="MathJax-Span-53" style="font-family: MathJax_Main; padding-left: 0.301em;">≤</span><span class="mi" id="MathJax-Span-54" style="font-family: MathJax_Math-italic; padding-left: 0.301em;">l</span><span class="mo" id="MathJax-Span-55" style="font-family: MathJax_Main; padding-left: 0.301em;"><</span><span class="mi" id="MathJax-Span-56" style="font-family: MathJax_Math-italic; padding-left: 0.301em;">r</span><span class="mo" id="MathJax-Span-57" style="font-family: MathJax_Main; padding-left: 0.301em;">≤</span><span class="mn" id="MathJax-Span-58" style="font-family: MathJax_Main; padding-left: 0.301em;">2</span><span class="mo" id="MathJax-Span-59" style="font-family: MathJax_Main; padding-left: 0.241em;">⋅</span><span class="msubsup" id="MathJax-Span-60" style="padding-left: 0.241em;"><span style="display: inline-block; position: relative; width: 1.432em; height: 0px;"><span style="position: absolute; clip: rect(3.158em, 1000.96em, 4.17em, -999.997em); top: -3.985em; left: 0em;"><span class="mn" id="MathJax-Span-61" style="font-family: MathJax_Main;">10</span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; top: -4.402em; left: 1.015em;"><span class="mn" id="MathJax-Span-62" style="font-size: 70.7%; font-family: MathJax_Main;">5</span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.211em; border-left: 0px solid; width: 0px; height: 1.361em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mn>1</mn><mo>≤</mo><mi>l</mi><mo><</mo><mi>r</mi><mo>≤</mo><mn>2</mn><mo>⋅</mo><msup><mn>10</mn><mn>5</mn></msup></math></span></span><script type="math/tex" id="MathJax-Element-13">1 \leq l < r \leq 2 \cdot 10^5</script>).</p></div><div class="output-specification"><div class="section-title">Output</div><p>For each test case, output a single integer — the minimum number of operations needed to make all numbers on the board equal <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-14-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>0</mn></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-63" style="width: 0.598em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.372em, 1000.42em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-64"><span class="mn" id="MathJax-Span-65" style="font-family: MathJax_Main;">0</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 1.004em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mn>0</mn></math></span></span><script type="math/tex" id="MathJax-Element-14">0</script>.</p></div><div class="sample-tests"><div class="section-title">Example</div><div class="sample-test"><div class="input"><div class="title">Input<div title="Copy" data-clipboard-target="#id004302314141906183" id="id004065344854040902" class="input-output-copier">Copy</div></div><pre id="id004302314141906183"><div class="test-example-line test-example-line-even test-example-line-0">4</div><div class="test-example-line test-example-line-odd test-example-line-1" style="">1 3</div><div class="test-example-line test-example-line-even test-example-line-2" style="">2 4</div><div class="test-example-line test-example-line-odd test-example-line-3" style="">199999 200000</div><div class="test-example-line test-example-line-even test-example-line-4" style="">19 84</div></pre></div><div class="output"><div class="title">Output<div title="Copy" data-clipboard-target="#id005777267915344002" id="id005785704180199143" class="input-output-copier">Copy</div></div><pre id="id005777267915344002">5636263</pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the first test case, we can perform <span class="MathJax_Preview" style="color: inherit;"></span><span class="MathJax" id="MathJax-Element-15-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML"><mn>5</mn></math>" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-66" style="width: 0.598em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0.479em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.372em, 1000.42em, 2.384em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-67"><span class="mn" id="MathJax-Span-68" style="font-family: MathJax_Main;">5</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.068em; border-left: 0px solid; width: 0px; height: 1.004em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"><mn>5</mn></math></span></span><script type="math/tex" id="MathJax-Element-15">5</script> operations as follows: <span class="MathJax_Preview" style="color: inherit;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-16-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><mn>1</mn><mo>,</mo><mn>2</mn><mo>,</mo><mn>3</mn><munderover><mo>&#x2192;</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>1</mn><mo>,</mo><mspace width="thinmathspace" /><mi>y</mi><mo>=</mo><mn>2</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em" /></munderover><mn>3</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>3</mn><munderover><mo>&#x2192;</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>0</mn><mo>,</mo><mspace width="thinmathspace" /><mi>y</mi><mo>=</mo><mn>3</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em" /></munderover><mn>1</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>3</mn><munderover><mo>&#x2192;</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>0</mn><mo>,</mo><mspace width="thinmathspace" /><mi>y</mi><mo>=</mo><mn>3</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em" /></munderover><mn>1</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>1</mn><munderover><mo>&#x2192;</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>0</mn><mo>,</mo><mspace width="thinmathspace" /><mi>y</mi><mo>=</mo><mn>1</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em" /></munderover><mn>0</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>1</mn><munderover><mo>&#x2192;</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>0</mn><mo>,</mo><mspace width="thinmathspace" /><mi>y</mi><mo>=</mo><mn>1</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em" /></munderover><mn>0</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>0</mn><mo>.</mo></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-69" style="width: 42.086em; display: inline-block;"><span style="display: inline-block; position: relative; width: 35.062em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.193em, 1035em, 3.396em, -999.997em); top: -2.199em; left: 0em;"><span class="mrow" id="MathJax-Span-70"><span class="mn" id="MathJax-Span-71" style="font-family: MathJax_Main;">1</span><span class="mo" id="MathJax-Span-72" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-73" style="font-family: MathJax_Main; padding-left: 0.182em;">2</span><span class="mo" id="MathJax-Span-74" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-75" style="font-family: MathJax_Main; padding-left: 0.182em;">3</span><span class="munderover" id="MathJax-Span-76" style="padding-left: 0.301em;"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.277em, 1003.4em, 4.17em, -999.997em); top: -3.985em; left: 0.003em;"><span class="mo" id="MathJax-Span-77" style=""><span style="display: inline-block; position: relative; width: 3.396em; height: 0px;"><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: -0.057em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: 2.443em;">→<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.42em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.955em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.432em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.967em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.336em, 1003.1em, 4.527em, -999.997em); top: -3.33em; left: 0em;"><span class="mpadded" id="MathJax-Span-78"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.336em, 1002.92em, 4.289em, -999.997em); top: -3.747em; left: 0.241em;"><span class="mrow" id="MathJax-Span-79"><span class="mi" id="MathJax-Span-80" style="font-size: 70.7%; font-family: MathJax_Math-italic;">x</span><span class="mo" id="MathJax-Span-81" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-82" style="font-size: 70.7%; font-family: MathJax_Main;">1</span><span class="mo" id="MathJax-Span-83" style="font-size: 70.7%; font-family: MathJax_Main;">,</span><span class="mspace" id="MathJax-Span-84" style="height: 0em; vertical-align: 0em; width: 0.182em; display: inline-block; overflow: hidden;"></span><span class="mi" id="MathJax-Span-85" style="font-size: 70.7%; font-family: MathJax_Math-italic;">y<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.003em;"></span></span><span class="mo" id="MathJax-Span-86" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-87" style="font-size: 70.7%; font-family: MathJax_Main;">2</span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.634em, 1000.24em, 4.17em, -999.997em); top: -4.699em; left: 1.491em;"><span class="mpadded" id="MathJax-Span-88"><span style="display: inline-block; position: relative; width: 0.539em; height: 0px;"><span style="position: absolute; clip: rect(3.812em, 1000em, 4.17em, -999.997em); top: -4.164em; left: 0.241em;"><span class="mrow" id="MathJax-Span-89"></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span class="mn" id="MathJax-Span-90" style="font-family: MathJax_Main; padding-left: 0.301em;">3</span><span class="mo" id="MathJax-Span-91" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-92" style="font-family: MathJax_Main; padding-left: 0.182em;">0</span><span class="mo" id="MathJax-Span-93" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-94" style="font-family: MathJax_Main; padding-left: 0.182em;">3</span><span class="munderover" id="MathJax-Span-95" style="padding-left: 0.301em;"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.277em, 1003.4em, 4.17em, -999.997em); top: -3.985em; left: 0.003em;"><span class="mo" id="MathJax-Span-96" style=""><span style="display: inline-block; position: relative; width: 3.396em; height: 0px;"><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: -0.057em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: 2.443em;">→<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.42em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.955em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.432em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.967em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.336em, 1003.16em, 4.527em, -999.997em); top: -3.33em; left: 0em;"><span class="mpadded" id="MathJax-Span-97"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.336em, 1002.92em, 4.289em, -999.997em); top: -3.747em; left: 0.241em;"><span class="mrow" id="MathJax-Span-98"><span class="mi" id="MathJax-Span-99" style="font-size: 70.7%; font-family: MathJax_Math-italic;">x</span><span class="mo" id="MathJax-Span-100" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-101" style="font-size: 70.7%; font-family: MathJax_Main;">0</span><span class="mo" id="MathJax-Span-102" style="font-size: 70.7%; font-family: MathJax_Main;">,</span><span class="mspace" id="MathJax-Span-103" style="height: 0em; vertical-align: 0em; width: 0.182em; display: inline-block; overflow: hidden;"></span><span class="mi" id="MathJax-Span-104" style="font-size: 70.7%; font-family: MathJax_Math-italic;">y<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.003em;"></span></span><span class="mo" id="MathJax-Span-105" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-106" style="font-size: 70.7%; font-family: MathJax_Main;">3</span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.634em, 1000.24em, 4.17em, -999.997em); top: -4.699em; left: 1.491em;"><span class="mpadded" id="MathJax-Span-107"><span style="display: inline-block; position: relative; width: 0.539em; height: 0px;"><span style="position: absolute; clip: rect(3.812em, 1000em, 4.17em, -999.997em); top: -4.164em; left: 0.241em;"><span class="mrow" id="MathJax-Span-108"></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span class="mn" id="MathJax-Span-109" style="font-family: MathJax_Main; padding-left: 0.301em;">1</span><span class="mo" id="MathJax-Span-110" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-111" style="font-family: MathJax_Main; padding-left: 0.182em;">0</span><span class="mo" id="MathJax-Span-112" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-113" style="font-family: MathJax_Main; padding-left: 0.182em;">3</span><span class="munderover" id="MathJax-Span-114" style="padding-left: 0.301em;"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.277em, 1003.4em, 4.17em, -999.997em); top: -3.985em; left: 0.003em;"><span class="mo" id="MathJax-Span-115" style=""><span style="display: inline-block; position: relative; width: 3.396em; height: 0px;"><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: -0.057em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: 2.443em;">→<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.42em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.955em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.432em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.967em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.336em, 1003.16em, 4.527em, -999.997em); top: -3.33em; left: 0em;"><span class="mpadded" id="MathJax-Span-116"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.336em, 1002.92em, 4.289em, -999.997em); top: -3.747em; left: 0.241em;"><span class="mrow" id="MathJax-Span-117"><span class="mi" id="MathJax-Span-118" style="font-size: 70.7%; font-family: MathJax_Math-italic;">x</span><span class="mo" id="MathJax-Span-119" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-120" style="font-size: 70.7%; font-family: MathJax_Main;">0</span><span class="mo" id="MathJax-Span-121" style="font-size: 70.7%; font-family: MathJax_Main;">,</span><span class="mspace" id="MathJax-Span-122" style="height: 0em; vertical-align: 0em; width: 0.182em; display: inline-block; overflow: hidden;"></span><span class="mi" id="MathJax-Span-123" style="font-size: 70.7%; font-family: MathJax_Math-italic;">y<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.003em;"></span></span><span class="mo" id="MathJax-Span-124" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-125" style="font-size: 70.7%; font-family: MathJax_Main;">3</span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.634em, 1000.24em, 4.17em, -999.997em); top: -4.699em; left: 1.491em;"><span class="mpadded" id="MathJax-Span-126"><span style="display: inline-block; position: relative; width: 0.539em; height: 0px;"><span style="position: absolute; clip: rect(3.812em, 1000em, 4.17em, -999.997em); top: -4.164em; left: 0.241em;"><span class="mrow" id="MathJax-Span-127"></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span class="mn" id="MathJax-Span-128" style="font-family: MathJax_Main; padding-left: 0.301em;">1</span><span class="mo" id="MathJax-Span-129" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-130" style="font-family: MathJax_Main; padding-left: 0.182em;">0</span><span class="mo" id="MathJax-Span-131" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-132" style="font-family: MathJax_Main; padding-left: 0.182em;">1</span><span class="munderover" id="MathJax-Span-133" style="padding-left: 0.301em;"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.277em, 1003.4em, 4.17em, -999.997em); top: -3.985em; left: 0.003em;"><span class="mo" id="MathJax-Span-134" style=""><span style="display: inline-block; position: relative; width: 3.396em; height: 0px;"><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: -0.057em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: 2.443em;">→<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.42em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.955em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.432em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.967em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.336em, 1003.1em, 4.527em, -999.997em); top: -3.33em; left: 0em;"><span class="mpadded" id="MathJax-Span-135"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.336em, 1002.86em, 4.289em, -999.997em); top: -3.747em; left: 0.241em;"><span class="mrow" id="MathJax-Span-136"><span class="mi" id="MathJax-Span-137" style="font-size: 70.7%; font-family: MathJax_Math-italic;">x</span><span class="mo" id="MathJax-Span-138" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-139" style="font-size: 70.7%; font-family: MathJax_Main;">0</span><span class="mo" id="MathJax-Span-140" style="font-size: 70.7%; font-family: MathJax_Main;">,</span><span class="mspace" id="MathJax-Span-141" style="height: 0em; vertical-align: 0em; width: 0.182em; display: inline-block; overflow: hidden;"></span><span class="mi" id="MathJax-Span-142" style="font-size: 70.7%; font-family: MathJax_Math-italic;">y<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.003em;"></span></span><span class="mo" id="MathJax-Span-143" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-144" style="font-size: 70.7%; font-family: MathJax_Main;">1</span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.634em, 1000.24em, 4.17em, -999.997em); top: -4.699em; left: 1.491em;"><span class="mpadded" id="MathJax-Span-145"><span style="display: inline-block; position: relative; width: 0.539em; height: 0px;"><span style="position: absolute; clip: rect(3.812em, 1000em, 4.17em, -999.997em); top: -4.164em; left: 0.241em;"><span class="mrow" id="MathJax-Span-146"></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span class="mn" id="MathJax-Span-147" style="font-family: MathJax_Main; padding-left: 0.301em;">0</span><span class="mo" id="MathJax-Span-148" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-149" style="font-family: MathJax_Main; padding-left: 0.182em;">0</span><span class="mo" id="MathJax-Span-150" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-151" style="font-family: MathJax_Main; padding-left: 0.182em;">1</span><span class="munderover" id="MathJax-Span-152" style="padding-left: 0.301em;"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.277em, 1003.4em, 4.17em, -999.997em); top: -3.985em; left: 0.003em;"><span class="mo" id="MathJax-Span-153" style=""><span style="display: inline-block; position: relative; width: 3.396em; height: 0px;"><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: -0.057em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; font-family: MathJax_Main; top: -3.985em; left: 2.443em;">→<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.42em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 0.955em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.432em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="font-family: MathJax_Main; position: absolute; top: -3.985em; left: 1.967em;">−<span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.336em, 1003.1em, 4.527em, -999.997em); top: -3.33em; left: 0em;"><span class="mpadded" id="MathJax-Span-154"><span style="display: inline-block; position: relative; width: 3.455em; height: 0px;"><span style="position: absolute; clip: rect(3.336em, 1002.86em, 4.289em, -999.997em); top: -3.747em; left: 0.241em;"><span class="mrow" id="MathJax-Span-155"><span class="mi" id="MathJax-Span-156" style="font-size: 70.7%; font-family: MathJax_Math-italic;">x</span><span class="mo" id="MathJax-Span-157" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-158" style="font-size: 70.7%; font-family: MathJax_Main;">0</span><span class="mo" id="MathJax-Span-159" style="font-size: 70.7%; font-family: MathJax_Main;">,</span><span class="mspace" id="MathJax-Span-160" style="height: 0em; vertical-align: 0em; width: 0.182em; display: inline-block; overflow: hidden;"></span><span class="mi" id="MathJax-Span-161" style="font-size: 70.7%; font-family: MathJax_Math-italic;">y<span style="display: inline-block; overflow: hidden; height: 1px; width: 0.003em;"></span></span><span class="mo" id="MathJax-Span-162" style="font-size: 70.7%; font-family: MathJax_Main;">=</span><span class="mn" id="MathJax-Span-163" style="font-size: 70.7%; font-family: MathJax_Main;">1</span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span><span style="position: absolute; clip: rect(3.634em, 1000.24em, 4.17em, -999.997em); top: -4.699em; left: 1.491em;"><span class="mpadded" id="MathJax-Span-164"><span style="display: inline-block; position: relative; width: 0.539em; height: 0px;"><span style="position: absolute; clip: rect(3.812em, 1000em, 4.17em, -999.997em); top: -4.164em; left: 0.241em;"><span class="mrow" id="MathJax-Span-165"></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span style="display: inline-block; width: 0px; height: 3.991em;"></span></span></span></span><span class="mn" id="MathJax-Span-166" style="font-family: MathJax_Main; padding-left: 0.301em;">0</span><span class="mo" id="MathJax-Span-167" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-168" style="font-family: MathJax_Main; padding-left: 0.182em;">0</span><span class="mo" id="MathJax-Span-169" style="font-family: MathJax_Main;">,</span><span class="mn" id="MathJax-Span-170" style="font-family: MathJax_Main; padding-left: 0.182em;">0</span><span class="mo" id="MathJax-Span-171" style="font-family: MathJax_Main;">.</span></span><span style="display: inline-block; width: 0px; height: 2.205em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -1.139em; border-left: 0px solid; width: 0px; height: 2.218em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><mn>1</mn><mo>,</mo><mn>2</mn><mo>,</mo><mn>3</mn><munderover><mo>→</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>1</mn><mo>,</mo><mspace width="thinmathspace"></mspace><mi>y</mi><mo>=</mo><mn>2</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em"></mpadded></munderover><mn>3</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>3</mn><munderover><mo>→</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>0</mn><mo>,</mo><mspace width="thinmathspace"></mspace><mi>y</mi><mo>=</mo><mn>3</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em"></mpadded></munderover><mn>1</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>3</mn><munderover><mo>→</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>0</mn><mo>,</mo><mspace width="thinmathspace"></mspace><mi>y</mi><mo>=</mo><mn>3</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em"></mpadded></munderover><mn>1</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>1</mn><munderover><mo>→</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>0</mn><mo>,</mo><mspace width="thinmathspace"></mspace><mi>y</mi><mo>=</mo><mn>1</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em"></mpadded></munderover><mn>0</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>1</mn><munderover><mo>→</mo><mpadded width="+0.611em" lspace="0.278em" voffset="-.24em"><mi>x</mi><mo>=</mo><mn>0</mn><mo>,</mo><mspace width="thinmathspace"></mspace><mi>y</mi><mo>=</mo><mn>1</mn></mpadded><mpadded width="+0.611em" lspace="0.278em" voffset=".15em"></mpadded></munderover><mn>0</mn><mo>,</mo><mn>0</mn><mo>,</mo><mn>0</mn><mo>.</mo></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-16"> 1,2,3 \xrightarrow[x=1,\,y=2]{} 3,0,3 \xrightarrow[x=0,\,y=3]{} 1,0,3 \xrightarrow[x=0,\,y=3]{} 1,0,1 \xrightarrow[x=0,\,y=1]{} 0,0,1 \xrightarrow[x=0,\,y=1]{} 0,0,0 .</script></p></div></div><p> </p></div>[964E.md](https://codeforces.com/contest/1999/problem/E)<h1 id="My-think"><a href="#My-think" class="headerlink" title="My think:"></a>My think:</h1><p>At first, I thought it was a simple simulation problem: calculate the number of times x when the smallest<br>number divided by 3 equals 0, and then the answer would be x * 2 plus the number of remaining times when<br>the left number divided by 3 equals 0. However, this approach is incorrect.</p><p>By utilizing the characteristics of exponential growth and performing some simple<br>calculations, we can quickly determine the minimum number of operations within a given range.<br>This method has a low time complexity and can efficiently handle large input ranges.</p><h1 id="Code"><a href="#Code" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> math</span><br><span class="line">t = <span class="built_in">int</span>(<span class="built_in">input</span>())</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(t):</span><br><span class="line"> num = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split()))</span><br><span class="line"> l = num[<span class="number">0</span>]</span><br><span class="line"> r = num[<span class="number">1</span>]</span><br><span class="line"> start_pow3 = <span class="number">1</span></span><br><span class="line"> cnt_start = <span class="number">1</span></span><br><span class="line"> <span class="keyword">while</span> start_pow3 <= (l / <span class="number">3</span>):</span><br><span class="line"> start_pow3 *= <span class="number">3</span></span><br><span class="line"> cnt_start += <span class="number">1</span></span><br><span class="line"> ans = cnt_start</span><br><span class="line"> pow3 = start_pow3</span><br><span class="line"> next_pow3 = start_pow3 * <span class="number">3</span></span><br><span class="line"> <span class="keyword">while</span> pow3 <= r:</span><br><span class="line"> ans += (<span class="built_in">min</span>(r + <span class="number">1</span>, next_pow3) - <span class="built_in">max</span>(l, pow3)) * cnt_start</span><br><span class="line"> cnt_start += <span class="number">1</span></span><br><span class="line"> pow3 *= <span class="number">3</span></span><br><span class="line"> next_pow3 *= <span class="number">3</span></span><br><span class="line"> <span class="built_in">print</span>(ans)</span><br><span class="line"></span><br></pre></td></tr></table></figure><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">min_operations_to_zero</span>(<span class="params">n</span>):</span><br><span class="line"> operations = <span class="number">0</span></span><br><span class="line"> <span class="keyword">while</span> n > <span class="number">0</span>:</span><br><span class="line"> n = n // <span class="number">3</span></span><br><span class="line"> operations += <span class="number">1</span></span><br><span class="line"> <span class="keyword">return</span> operations</span><br><span class="line"></span><br><span class="line">t = <span class="built_in">int</span>(<span class="built_in">input</span>())</span><br><span class="line">results = []</span><br><span class="line"><span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(t):</span><br><span class="line"> l, r = <span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">input</span>().split())</span><br><span class="line"> total_operations = <span class="number">0</span></span><br><span class="line"> oper = min_operations_to_zero(l)</span><br><span class="line"> <span class="keyword">for</span> n <span class="keyword">in</span> <span class="built_in">range</span>(l+<span class="number">1</span>, r+<span class="number">1</span>):</span><br><span class="line"> total_operations += min_operations_to_zero(n)</span><br><span class="line"> total_operations += oper*<span class="number">2</span></span><br><span class="line"> results.append(total_operations)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> result <span class="keyword">in</span> results:</span><br><span class="line"> <span class="built_in">print</span>(result)</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="Question"><a href="#Question" class="headerlink" title="Question:"></a>Question:</h1><div class="ttypography"><div class="problem-st</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="Answer" scheme="https://longsizhuo.github.io/tags/Answer/"/>
</entry>
<entry>
<title>994.Rotten orange</title>
<link href="https://longsizhuo.github.io/post/56e64fdd.html"/>
<id>https://longsizhuo.github.io/post/56e64fdd.html</id>
<published>2024-05-13T14:00:00.000Z</published>
<updated>2024-08-07T09:57:45.056Z</updated>
<content type="html"><![CDATA[<h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p>“””</p><p>Given <code>m x n</code> grid <meta charset="UTF-8" /> <code>grid</code> middle,Each cell can have one of the following three values:</p><ul> <li>value <code>0</code> Represents the empty unit;</li> <li>value <code>1</code> Represents fresh oranges;</li> <li>value <code>2</code> 代表Rotten orange。</li> </ul><p>every minute,Rotten orange <strong>around 4 Adjacent in this direction</strong> Fresh oranges will rot。</p><p>return <em>直到单元格middle没有新鲜橘子为止所必须经过的最小分钟数。If it is impossible,return <code>-1</code></em> 。</p><p> </p><p><strong>Exemplary example 1:</strong></p><p><strong><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/16/oranges.png" style="height: 137px; width: 650px;" /></strong></p><pre><strong>enter:</strong>grid = [[2,1,1],[1,1,0],[0,1,1]]<strong>Output:</strong>4</pre><p><strong>Exemplary example 2:</strong></p><pre><strong>enter:</strong>grid = [[2,1,1],[0,1,1],[1,0,1]]<strong>Output:</strong>-1<strong>explain:</strong>Orange in the lower left corner(First 2 OK, First 0 List)Never rot,Because rotten will only happen in 4 In the direction。</pre><p><strong>Exemplary example 3:</strong></p><pre><strong>enter:</strong>grid = [[0,2]]<strong>Output:</strong>0<strong>explain:</strong>because 0 There is no fresh orange in minutes,So the answer is 0 。</pre><p> </p><p><strong>hint:</strong></p><ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 <= m, n <= 10</code></li> <li><code>grid[i][j]</code> Only for <code>0</code>、<code>1</code> or <code>2</code></li> </ul><div><div>Related Topics</div><div><li>Priority search</li><li>Array</li><li>matrix</li></div></div><br><div><li>👍 872</li><li>👎 0</li></div>"""<h1 id="Thought:"><a href="#Thought:" class="headerlink" title="Thought:"></a>Thought:</h1><p>这个问题可以用Priority search(BFS)To solve。We need to track the spread of rotten oranges,Record time,And check if there is a fresh orange that cannot be rotten。The initial idea of the original idea:</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">orangesRotting</span>(<span class="params">self, grid: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -> <span class="built_in">int</span>:</span><br><span class="line"> bad_orange = []</span><br><span class="line"> <span class="comment"># 找到所有初始Rotten orange</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(grid)):</span><br><span class="line"> <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(grid[<span class="number">0</span>])):</span><br><span class="line"> <span class="keyword">if</span> grid[i][j] == <span class="number">2</span>:</span><br><span class="line"> <span class="comment"># 存入初始队List</span></span><br><span class="line"> bad_orange.append((i, j))</span><br></pre></td></tr></table></figure><p>Similar to multi -threaded,每个线程存入一个初始队List,初始队List通过BFSGradual diffusion</p><h1 id="Code:"><a href="#Code:" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> deque</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">orangesRotting</span>(<span class="params">self, grid: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -> <span class="built_in">int</span>:</span><br><span class="line"> bad_orange = deque()</span><br><span class="line"> fresh_oranges = <span class="number">0</span></span><br><span class="line"> rows, cols = <span class="built_in">len</span>(grid), <span class="built_in">len</span>(grid[<span class="number">0</span>])</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># 找到所有初始Rotten orange,And calculate the number of fresh oranges</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(rows):</span><br><span class="line"> <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(cols):</span><br><span class="line"> <span class="keyword">if</span> grid[i][j] == <span class="number">2</span>:</span><br><span class="line"> bad_orange.append((i, j))</span><br><span class="line"> <span class="keyword">elif</span> grid[i][j] == <span class="number">1</span>:</span><br><span class="line"> fresh_oranges += <span class="number">1</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># 方向Array:up down left right</span></span><br><span class="line"> directions = [(<span class="number">0</span>, <span class="number">1</span>), (<span class="number">1</span>, <span class="number">0</span>), (<span class="number">0</span>, -<span class="number">1</span>), (-<span class="number">1</span>, <span class="number">0</span>)]</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># If there is no fresh orange,直接return 0</span></span><br><span class="line"> <span class="keyword">if</span> fresh_oranges == <span class="number">0</span>:</span><br><span class="line"> <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment"># BFS</span></span><br><span class="line"> minutes = <span class="number">0</span></span><br><span class="line"> <span class="keyword">while</span> bad_orange:</span><br><span class="line"> minutes += <span class="number">1</span></span><br><span class="line"> <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(bad_orange)):</span><br><span class="line"> x, y = bad_orange.popleft()</span><br><span class="line"> <span class="keyword">for</span> dx, dy <span class="keyword">in</span> directions:</span><br><span class="line"> nx, ny = x + dx, y + dy</span><br><span class="line"> <span class="keyword">if</span> <span class="number">0</span> <= nx < rows <span class="keyword">and</span> <span class="number">0</span> <= ny < cols <span class="keyword">and</span> grid[nx][ny] == <span class="number">1</span>:</span><br><span class="line"> grid[nx][ny] = <span class="number">2</span></span><br><span class="line"> fresh_oranges -= <span class="number">1</span></span><br><span class="line"> bad_orange.append((nx, ny))</span><br><span class="line"> </span><br><span class="line"> <span class="comment"># If there are fresh oranges,return -1</span></span><br><span class="line"> <span class="keyword">return</span> minutes - <span class="number">1</span> <span class="keyword">if</span> fresh_oranges == <span class="number">0</span> <span class="keyword">else</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> (</span><br><span class="line"><span class="string">"sync"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">orangesRotting</span><span class="params">(grid [][]<span class="type">int</span>)</span></span> <span class="type">int</span> {</span><br><span class="line">rows, cols := <span class="built_in">len</span>(grid), <span class="built_in">len</span>(grid[<span class="number">0</span>])</span><br><span class="line">badOranges := <span class="built_in">make</span>([][<span class="number">2</span>]<span class="type">int</span>, <span class="number">0</span>)</span><br><span class="line">freshOranges := <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 找到所有初始Rotten orange,And calculate the number of fresh oranges</span></span><br><span class="line"><span class="keyword">for</span> r := <span class="number">0</span>; r < rows; r++ {</span><br><span class="line"><span class="keyword">for</span> c := <span class="number">0</span>; c < cols; c++ {</span><br><span class="line"><span class="keyword">if</span> grid[r][c] == <span class="number">2</span> {</span><br><span class="line">badOranges = <span class="built_in">append</span>(badOranges, [<span class="number">2</span>]<span class="type">int</span>{r, c})</span><br><span class="line">} <span class="keyword">else</span> <span class="keyword">if</span> grid[r][c] == <span class="number">1</span> {</span><br><span class="line">freshOranges += <span class="number">1</span></span><br><span class="line">}</span><br><span class="line">}</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// If there is no fresh orange,直接return 0</span></span><br><span class="line"><span class="keyword">if</span> freshOranges == <span class="number">0</span> {</span><br><span class="line"><span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">directions := [][<span class="number">2</span>]<span class="type">int</span>{{<span class="number">0</span>, <span class="number">1</span>}, {<span class="number">1</span>, <span class="number">0</span>}, {<span class="number">0</span>, <span class="number">-1</span>}, {<span class="number">-1</span>, <span class="number">0</span>}}</span><br><span class="line">minutes := <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> wg sync.WaitGroup</span><br><span class="line"></span><br><span class="line"><span class="comment">// BFS</span></span><br><span class="line"><span class="keyword">for</span> <span class="built_in">len</span>(badOranges) > <span class="number">0</span> {</span><br><span class="line">minutes++</span><br><span class="line">nextBadOranges := <span class="built_in">make</span>([][<span class="number">2</span>]<span class="type">int</span>, <span class="number">0</span>)</span><br><span class="line"><span class="keyword">for</span> _, orange := <span class="keyword">range</span> badOranges {</span><br><span class="line">x, y := orange[<span class="number">0</span>], orange[<span class="number">1</span>]</span><br><span class="line">wg.Add(<span class="number">1</span>)</span><br><span class="line"><span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">(x, y <span class="type">int</span>)</span></span> {</span><br><span class="line"><span class="keyword">defer</span> wg.Done()</span><br><span class="line"><span class="keyword">for</span> _, d := <span class="keyword">range</span> directions {</span><br><span class="line">nx, ny := x+d[<span class="number">0</span>], y+d[<span class="number">1</span>]</span><br><span class="line"><span class="keyword">if</span> nx >= <span class="number">0</span> && nx < rows && ny >= <span class="number">0</span> && ny < cols && grid[nx][ny] == <span class="number">1</span> {</span><br><span class="line">grid[nx][ny] = <span class="number">2</span></span><br><span class="line">nextBadOranges = <span class="built_in">append</span>(nextBadOranges, [<span class="number">2</span>]<span class="type">int</span>{nx, ny})</span><br><span class="line">freshOranges--</span><br><span class="line">}</span><br><span class="line">}</span><br><span class="line">}(x, y)</span><br><span class="line">}</span><br><span class="line">wg.Wait()</span><br><span class="line">badOranges = nextBadOranges</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// If there are fresh oranges,return -1</span></span><br><span class="line"><span class="keyword">if</span> freshOranges > <span class="number">0</span> {</span><br><span class="line"><span class="keyword">return</span> <span class="number">-1</span></span><br><span class="line">}</span><br><span class="line"><span class="keyword">return</span> minutes - <span class="number">1</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p>“””</p>
<p>Given&nbsp;<code>m x n</code>&nbsp;grid
<m</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="BFS" scheme="https://longsizhuo.github.io/tags/BFS/"/>
<category term="Bilateral queue" scheme="https://longsizhuo.github.io/tags/Bilateral-queue/"/>
</entry>
<entry>
<title>1017. Negative binary conversion</title>
<link href="https://longsizhuo.github.io/post/dce95dce.html"/>
<id>https://longsizhuo.github.io/post/dce95dce.html</id>
<published>2023-12-31T13:00:00.000Z</published>
<updated>2024-08-07T09:57:45.030Z</updated>
<content type="html"><![CDATA[<h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><a href="https://leetcode.cn/problems/convert-to-base-2/description/?envType=daily-question&envId=2024-04-28">1017. Negative binary conversion</a></p><h1 id="Thought:"><a href="#Thought:" class="headerlink" title="Thought:"></a>Thought:</h1><p>The difference from binary is just not always//2,It’s every number//-1</p><h1 id="Code:"><a href="#Code:" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">baseNeg2</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -> <span class="built_in">str</span>:</span><br><span class="line"> k = <span class="number">1</span></span><br><span class="line"> ans = []</span><br><span class="line"> <span class="keyword">while</span> n:</span><br><span class="line"> <span class="keyword">if</span> n % <span class="number">2</span>:</span><br><span class="line"> ans.append(<span class="string">'1'</span>)</span><br><span class="line"> n -= k</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> ans.append(<span class="string">'0'</span>)</span><br><span class="line"> n //= <span class="number">2</span></span><br><span class="line"> k *= -<span class="number">1</span></span><br><span class="line"> <span class="keyword">return</span> <span class="string">''</span>.join(ans[::-<span class="number">1</span>]) <span class="keyword">or</span> <span class="string">'0'</span> </span><br></pre></td></tr></table></figure><figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">impl</span> <span class="title class_">Solution</span> {</span><br><span class="line"> <span class="keyword">pub</span> <span class="keyword">fn</span> <span class="title function_">base_neg2</span>(<span class="keyword">mut</span> n: <span class="type">i32</span>) <span class="punctuation">-></span> <span class="type">String</span> {</span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">ans</span> = <span class="type">Vec</span>::<span class="title function_ invoke__">new</span>();</span><br><span class="line"> <span class="keyword">while</span> n != <span class="number">0</span> {</span><br><span class="line"> <span class="keyword">if</span> n % <span class="number">2</span> != <span class="number">0</span> {</span><br><span class="line"> ans.<span class="title function_ invoke__">push</span>(<span class="string">'1'</span>);</span><br><span class="line"> n = (n - <span class="number">1</span>) / -<span class="number">2</span>;</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> ans.<span class="title function_ invoke__">push</span>(<span class="string">'0'</span>);</span><br><span class="line"> n /= -<span class="number">2</span>;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> ans.<span class="title function_ invoke__">is_empty</span>() {</span><br><span class="line"> ans.<span class="title function_ invoke__">push</span>(<span class="string">'0'</span>);</span><br><span class="line"> }</span><br><span class="line"> ans.<span class="title function_ invoke__">reverse</span>();</span><br><span class="line"> ans.<span class="title function_ invoke__">iter</span>().<span class="title function_ invoke__">collect</span>()</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><a href="https://leetcode.cn/problems/convert-to-base-</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="answer" scheme="https://longsizhuo.github.io/tags/answer/"/>
</entry>
<entry>
<title>1017.Negative binary conversion</title>
<link href="https://longsizhuo.github.io/post/80cafdc8.html"/>
<id>https://longsizhuo.github.io/post/80cafdc8.html</id>
<published>2023-12-31T13:00:00.000Z</published>
<updated>2024-08-07T09:57:45.030Z</updated>
<content type="html"><![CDATA[<h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p>Give you an integer <code>n</code> ,Return to the integer in the form of a binary string <strong>Negative binary(<code>base -2</code>)</strong>express。</p><p><strong>Notice,</strong>Unless the string is <code>"0"</code>,Otherwise, the returned string cannot contain the front guide zero。</p><p> </p><p><strong>Exemplary example 1:</strong></p><pre><strong>enter:</strong>n = 2<strong>Output:</strong>"110"<strong>explain:</strong>(-2)<sup>2</sup> + (-2)<sup>1</sup> = 2</pre><p><strong>Exemplary example 2:</strong></p><pre><strong>enter:</strong>n = 3<strong>Output:</strong>"111"<strong>explain:</strong>(-2)<sup>2</sup> + (-2)<sup>1</sup> + (-2)<sup>0</sup> = 3</pre><p><strong>Exemplary example 3:</strong></p><pre><strong>enter:</strong>n = 4<strong>Output:</strong>"100"<strong>explain:</strong>(-2)<sup>2</sup> = 4</pre><p> </p><p><strong>hint:</strong></p><ul> <li><code>0 <= n <= 10<sup>9</sup></code></li> </ul><div><div>Related Topics</div><div><li>math</li></div></div><br><div><li>👍 111</li><li>👎 0</li></div>[1017.Negative binary conversion.md]()<h1 id="Thought:"><a href="#Thought:" class="headerlink" title="Thought:"></a>Thought:</h1><p>We can judge n Every bit from low to high,If the bit is 1,Then the answer is 1,Otherwise 0。If the bit is 1,So we need to n minus k。Next we update n=⌊n/2⌋, k=−k。Continue to judge the next。<br>at last,We will return to the answer。<br>time complexity O(logn),in n For the given integer。Ignore the space consumption of the answer,Spatial complexity O(1)。</p><h1 id="Code:"><a href="#Code:" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">baseNeg2</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -> <span class="built_in">str</span>:</span><br><span class="line"> k = <span class="number">1</span></span><br><span class="line"> ans = []</span><br><span class="line"> <span class="keyword">while</span> n:</span><br><span class="line"> <span class="keyword">if</span> n % <span class="number">2</span>:</span><br><span class="line"> ans.append(<span class="string">'1'</span>)</span><br><span class="line"> n -= k</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> ans.append(<span class="string">'0'</span>)</span><br><span class="line"> n //= <span class="number">2</span></span><br><span class="line"> k *= -<span class="number">1</span></span><br><span class="line"> <span class="keyword">return</span> <span class="string">''</span>.join(ans[::-<span class="number">1</span>]) <span class="keyword">or</span> <span class="string">'0'</span></span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p>Give you an integer <code>n</code> ,Return to the inte</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="answer" scheme="https://longsizhuo.github.io/tags/answer/"/>
</entry>
<entry>
<title>1124. The longest period of performance One question daily</title>
<link href="https://longsizhuo.github.io/post/a5d1dfda.html"/>
<id>https://longsizhuo.github.io/post/a5d1dfda.html</id>
<published>2023-12-31T13:00:00.000Z</published>
<updated>2024-08-07T09:57:45.030Z</updated>
<content type="html"><![CDATA[<h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-15.png" alt="2023-02-15.png"><br><a href="https://leetcode.cn/problems/longest-well-performing-interval/description/">1124. The longest period of performance.md</a></p><h1 id="Thought:"><a href="#Thought:" class="headerlink" title="Thought:"></a>Thought:</h1><p>This question is not,I thought it was a double pointer but timeout over time,结果是Prefix and算法。The following is<a href="https://leetcode.cn/problems/longest-well-performing-interval/solutions/2110211/liang-chong-zuo-fa-liang-zhang-tu-miao-d-hysl/">Spiritual god</a>Solution<br>通过Prefix and,我们可以把Elements and elements of sub -array转换成两个Prefix and的差,Right now<br>$$<br>\sum_{j=left}^{right} nums[j] = \sum_{j=0}^{right} nums[j]− \sum_{j=0}^{left-1} nums[j]=s[right+1]−s[left]<br>$$<br>Now that I said it「Elements and elements of sub -array」,那么利用Prefix and s,Turn the problem to:<br>Find two bidding i and j,satisfy j<ij<ij<i and s[j]<s[i],maximize i−jValue。</p><p><img src="https://pic.leetcode.cn/1676294271-XVWmuP-1124-3.png"></p><h1 id="Code:"><a href="#Code:" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><figcaption><span>Double pointer</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">longestWPI</span>(<span class="params">self, hours: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -> <span class="built_in">int</span>:</span><br><span class="line"> ans = <span class="number">0</span></span><br><span class="line"> <span class="keyword">for</span> index, i <span class="keyword">in</span> <span class="built_in">enumerate</span>(hours):</span><br><span class="line"> count = <span class="number">0</span></span><br><span class="line"> j = index</span><br><span class="line"> <span class="keyword">while</span> j < <span class="built_in">len</span>(hours):</span><br><span class="line"> <span class="keyword">if</span> hours[j] <= <span class="number">8</span>:</span><br><span class="line"> count -= <span class="number">1</span></span><br><span class="line"> <span class="keyword">elif</span> hours[j] > <span class="number">8</span>:</span><br><span class="line"> count += <span class="number">1</span></span><br><span class="line"> <span class="keyword">if</span> count > <span class="number">0</span>:</span><br><span class="line"> ans = <span class="built_in">max</span>(ans, j - index + <span class="number">1</span>)</span><br><span class="line"> j += <span class="number">1</span></span><br><span class="line"> <span class="keyword">return</span> ans</span><br></pre></td></tr></table></figure><figure class="highlight python"><figcaption><span>Prefix and</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">longestWPI</span>(<span class="params">self, hours: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -> <span class="built_in">int</span>:</span><br><span class="line"> n = <span class="built_in">len</span>(hours)</span><br><span class="line"> s = [<span class="number">0</span>] * (n + <span class="number">1</span>)</span><br><span class="line"> st = [<span class="number">0</span>]</span><br><span class="line"> <span class="keyword">for</span> j, h <span class="keyword">in</span> <span class="built_in">enumerate</span>(hours, <span class="number">1</span>):</span><br><span class="line"> s[j] = s[j - <span class="number">1</span>] + (<span class="number">1</span> <span class="keyword">if</span> h > <span class="number">8</span> <span class="keyword">else</span> -<span class="number">1</span>)</span><br><span class="line"> <span class="keyword">if</span> s[j] < s[st[-<span class="number">1</span>]]:</span><br><span class="line"> st.append(j)</span><br><span class="line"> ans = <span class="number">0</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n, <span class="number">0</span> , -<span class="number">1</span>):</span><br><span class="line"> <span class="keyword">while</span> st <span class="keyword">and</span> s[i] > s[st[-<span class="number">1</span>]]:</span><br><span class="line"> ans = <span class="built_in">max</span>(ans, i-st.pop())</span><br><span class="line"> <span class="keyword">return</span> ans</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-15.png" alt="2023-02-1</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="answer" scheme="https://longsizhuo.github.io/tags/answer/"/>
<category term="Prefix and" scheme="https://longsizhuo.github.io/tags/Prefix-and/"/>
</entry>
<entry>
<title>1138. The path on the letter board One question daily</title>
<link href="https://longsizhuo.github.io/post/fd471847.html"/>
<id>https://longsizhuo.github.io/post/fd471847.html</id>
<published>2023-12-31T13:00:00.000Z</published>
<updated>2024-08-07T09:57:45.031Z</updated>
<content type="html"><![CDATA[<h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-12.png" alt="2023-02-12.png"><br><a href="https://leetcode.cn/problems/alphabet-board-path/description/">1138. The path on the letter board One question daily.md</a></p><h1 id="Thought:"><a href="#Thought:" class="headerlink" title="Thought:"></a>Thought:</h1><p>Read the wrong questions,According to the method of random letters above the subtitle version。but<code>z</code>Special circumstances are not considered,I thought about it later,Just turn the column into a line,Time complexity isOn3<br>。Look atylbs answer,Use directlyasciiThe code watch simulates a letter board。</p><blockquote><p>From the starting point (0,0)(0, 0)(0,0) Set off,Simulate each step of movement,Style the movement of each step into the answer。Pay attention to the direction of moving“Left、superior、right、Down”Order。</p></blockquote><h1 id="Code:"><a href="#Code:" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">alphabetBoardPath</span>(<span class="params">self, target: <span class="built_in">str</span></span>) -> <span class="built_in">str</span>:</span><br><span class="line"> str1 = <span class="string">""</span></span><br><span class="line"> board = [<span class="string">"abcde"</span>,</span><br><span class="line"> <span class="string">"fghij"</span>,</span><br><span class="line"> <span class="string">"klmno"</span>,</span><br><span class="line"> <span class="string">"pqrst"</span>,</span><br><span class="line"> <span class="string">"uvwxy"</span>,</span><br><span class="line"> <span class="string">"z"</span>]</span><br><span class="line"> now_i = <span class="number">0</span></span><br><span class="line"> now_j = <span class="number">0</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> board:</span><br><span class="line"> <span class="keyword">for</span> j,value <span class="keyword">in</span> <span class="built_in">enumerate</span>(i):</span><br><span class="line"> <span class="keyword">pass</span></span><br><span class="line"> <span class="keyword">for</span> char <span class="keyword">in</span> target:</span><br><span class="line"> <span class="comment"># See which line is</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(board)):</span><br><span class="line"> <span class="keyword">if</span> char <span class="keyword">in</span> board[i]:</span><br><span class="line"> <span class="keyword">if</span> i - now_i > <span class="number">0</span>:</span><br><span class="line"> str1 += <span class="string">'D'</span> * (i - now_i)</span><br><span class="line"> <span class="keyword">if</span> i - now_i < <span class="number">0</span>:</span><br><span class="line"> str1 += <span class="string">'U'</span> * (now_i - i)</span><br><span class="line"> now_i = i</span><br><span class="line"> <span class="comment"># Which column</span></span><br><span class="line"> <span class="keyword">for</span> j, value <span class="keyword">in</span> <span class="built_in">enumerate</span>(board[i]):</span><br><span class="line"> <span class="keyword">if</span> value == char:</span><br><span class="line"> <span class="keyword">if</span> j - now_j > <span class="number">0</span>:</span><br><span class="line"> str1 += <span class="string">'R'</span> * (j - now_j)</span><br><span class="line"> <span class="keyword">if</span> j - now_j < <span class="number">0</span>:</span><br><span class="line"> str1 += <span class="string">'L'</span> * (now_j - j)</span><br><span class="line"> str1 += <span class="string">'!'</span></span><br><span class="line"> now_j = j</span><br><span class="line"> <span class="keyword">return</span> str1</span><br></pre></td></tr></table></figure><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">alphabetBoardPath</span>(<span class="params">self, target: <span class="built_in">str</span></span>) -> <span class="built_in">str</span>:</span><br><span class="line"> i = j = <span class="number">0</span></span><br><span class="line"> ans = []</span><br><span class="line"> <span class="keyword">for</span> char <span class="keyword">in</span> target:</span><br><span class="line"> v = <span class="built_in">ord</span>(char) - <span class="built_in">ord</span>(<span class="string">"a"</span>)</span><br><span class="line"> x, y = v // <span class="number">5</span>, v % <span class="number">5</span></span><br><span class="line"> <span class="keyword">while</span> j > y:</span><br><span class="line"> j -= <span class="number">1</span></span><br><span class="line"> ans.append(<span class="string">"L"</span>)</span><br><span class="line"> <span class="keyword">while</span> i > x:</span><br><span class="line"> i -= <span class="number">1</span></span><br><span class="line"> ans.append(<span class="string">"U"</span>)</span><br><span class="line"> <span class="keyword">while</span> j < y:</span><br><span class="line"> j += <span class="number">1</span></span><br><span class="line"> ans.append(<span class="string">"R"</span>)</span><br><span class="line"> <span class="keyword">while</span> i < x:</span><br><span class="line"> i += <span class="number">1</span></span><br><span class="line"> ans.append(<span class="string">"D"</span>)</span><br><span class="line"> ans.append(<span class="string">"!"</span>)</span><br><span class="line"> <span class="keyword">return</span> <span class="string">""</span>.join(ans)</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-12.png" alt="2023-02-1</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="answer" scheme="https://longsizhuo.github.io/tags/answer/"/>
</entry>
<entry>
<title>1139. The greatest 1 Formation of the border One question daily</title>
<link href="https://longsizhuo.github.io/post/eb193c1f.html"/>
<id>https://longsizhuo.github.io/post/eb193c1f.html</id>
<published>2023-12-31T13:00:00.000Z</published>
<updated>2024-08-07T09:57:45.031Z</updated>
<content type="html"><![CDATA[<h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-17.png" alt="2023-02-17.png"><br><a href="https://leetcode.cn/problems/largest-1-bordered-square/description/">1139. The greatest 1 Formation of the border.md</a></p><h1 id="Thought:"><a href="#Thought:" class="headerlink" title="Thought:"></a>Thought:</h1><p>quiz6 Simple version,Prefix and求解。It should be noted that the upper left corner is0 Special circumstances are not considered,<br>Need to verify # superior Left Down right Four -edge 1 The number of individuals d<br><img src="https://pic.leetcode.cn/1676448329-qJcoyK-1139.png"></p><h1 id="Code:"><a href="#Code:" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><figcaption><span>错误Code</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">largest1BorderedSquare</span>(<span class="params">self, grid: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -> <span class="built_in">int</span>:</span><br><span class="line"> matrix_heng = copy.deepcopy(grid)</span><br><span class="line"> matrix_su = copy.deepcopy(grid)</span><br><span class="line"> ans = <span class="number">0</span></span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">len</span>(grid) == <span class="number">1</span>:</span><br><span class="line"> <span class="keyword">if</span> <span class="number">1</span> <span class="keyword">in</span> grid[<span class="number">0</span>]:</span><br><span class="line"> <span class="keyword">return</span> <span class="number">1</span></span><br><span class="line"> <span class="keyword">else</span>:<span class="keyword">return</span> <span class="number">0</span></span><br><span class="line"> <span class="keyword">for</span> ind, i <span class="keyword">in</span> <span class="built_in">enumerate</span>(grid):</span><br><span class="line"> <span class="keyword">for</span> index <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(i)):</span><br><span class="line"> <span class="comment"># Each line adds</span></span><br><span class="line"> <span class="keyword">if</span> index >= <span class="number">1</span>:</span><br><span class="line"> matrix_heng[ind][index] += matrix_heng[ind][index-<span class="number">1</span>]</span><br><span class="line"> <span class="comment"># Add each column</span></span><br><span class="line"> <span class="keyword">if</span> ind >= <span class="number">1</span>:</span><br><span class="line"> matrix_su[ind][index] += matrix_su[ind-<span class="number">1</span>][index]</span><br><span class="line"> <span class="built_in">print</span>(matrix_heng, matrix_su)</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(grid)):</span><br><span class="line"> <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(grid[i])):</span><br><span class="line"> minus = <span class="built_in">min</span>(matrix_heng[i][j], matrix_su[i][j])</span><br><span class="line"> <span class="keyword">try</span>:</span><br><span class="line"> <span class="keyword">if</span> grid[i-minus+<span class="number">1</span>][j-minus+<span class="number">1</span>] == <span class="number">1</span> <span class="keyword">and</span> i >= minus-<span class="number">1</span> <span class="keyword">and</span> j >= minus-<span class="number">1</span>:</span><br><span class="line"> ans = <span class="built_in">max</span>(ans, minus ** <span class="number">2</span>)</span><br><span class="line"> <span class="keyword">except</span>:</span><br><span class="line"> <span class="keyword">pass</span></span><br><span class="line"> <span class="keyword">return</span> ans</span><br></pre></td></tr></table></figure><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">largest1BorderedSquare</span>(<span class="params">self, grid: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -> <span class="built_in">int</span>:</span><br><span class="line"> m, n = <span class="built_in">len</span>(grid), <span class="built_in">len</span>(grid[<span class="number">0</span>])</span><br><span class="line"> rs = [<span class="built_in">list</span>(accumulate(row, initial=<span class="number">0</span>)) <span class="keyword">for</span> row <span class="keyword">in</span> grid] <span class="comment"># 每行的Prefix and</span></span><br><span class="line"> cs = [<span class="built_in">list</span>(accumulate(col, initial=<span class="number">0</span>)) <span class="keyword">for</span> col <span class="keyword">in</span> <span class="built_in">zip</span>(*grid)] <span class="comment"># 每列的Prefix and</span></span><br><span class="line"> <span class="keyword">for</span> d <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">min</span>(m, n), <span class="number">0</span>, -<span class="number">1</span>): <span class="comment"># From large to small enumeration square edges d</span></span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(m - d + <span class="number">1</span>):</span><br><span class="line"> <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(n - d + <span class="number">1</span>): <span class="comment"># 枚举正方形Leftsuperior角坐标 (i,j)</span></span><br><span class="line"> <span class="comment"># superior Left Down right Four -edge 1 The number of individuals d</span></span><br><span class="line"> <span class="keyword">if</span> rs[i][j + d] - rs[i][j] == d <span class="keyword">and</span> \</span><br><span class="line"> cs[j][i + d] - cs[j][i] == d <span class="keyword">and</span> \</span><br><span class="line"> rs[i + d - <span class="number">1</span>][j + d] - rs[i + d - <span class="number">1</span>][j] == d <span class="keyword">and</span> \</span><br><span class="line"> cs[j + d - <span class="number">1</span>][i + d] - cs[j + d - <span class="number">1</span>][i] == d:</span><br><span class="line"> <span class="keyword">return</span> d * d</span><br><span class="line"> <span class="keyword">return</span> <span class="number">0</span></span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-17.png" alt="2023-02-1</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="answer" scheme="https://longsizhuo.github.io/tags/answer/"/>
<category term="Prefix and" scheme="https://longsizhuo.github.io/tags/Prefix-and/"/>
</entry>
<entry>
<title>1234. Replace the sub -string to get a balanced string One question daily</title>
<link href="https://longsizhuo.github.io/post/56d97dcf.html"/>
<id>https://longsizhuo.github.io/post/56d97dcf.html</id>
<published>2023-12-31T13:00:00.000Z</published>
<updated>2024-08-07T09:57:45.032Z</updated>
<content type="html"><![CDATA[<h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-13.png" alt="2023-02-13.png"><br><a href="https://leetcode.cn/problems/replace-the-substring-for-balanced-string/description/">1234. Replace the sub -string to get a balanced string.md</a></p><h1 id="Thought:"><a href="#Thought:" class="headerlink" title="Thought:"></a>Thought:</h1><p><code>all()</code>:if bool(x) For all the values in iterative objects x All for True,Then return True。 if可迭代对象为空,Then return True。</p><p>Tongxiang dual pointer,The solution of the spiritual god of this question。<br>If in this string,These four characters happen just to appear n/4 Second-rate,Then it is one「Balanced string」。<br>if在待替换子串之外的任意字符的出现Second-rate数都<strong>Exceed</strong> $m=\dfrac{n}{4}$<br>,So no matter how you replace it,都无法make这个字符的出现Second-rate数等于m。<br>on the other hand,if在待替换子串之外的任意字符的出现Second-rate数都<strong>不Exceed</strong> m,</p><blockquote><p>So it can be replaced ,make s 为Balanced string,即每个字符的出现Second-rate数均为 m。<br>For this question,The left and right end points of the sub -string are left and right,enumerate right,<br>if子串外的任意字符的出现Second-rate数都不Exceedm,The explanation from left arrive<br>rightThis sub -string can be to replace the sub -string,Length right−left+1<br>Update the minimum value of the answer,Move to the right left,Sumid sub -string length。</p></blockquote><h1 id="Code:"><a href="#Code:" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">balancedString</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -> <span class="built_in">int</span>:</span><br><span class="line"> s_c = Counter(s)</span><br><span class="line"> n = <span class="built_in">len</span>(s)</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">all</span>(s_c[v] <= n//<span class="number">4</span> <span class="keyword">for</span> v <span class="keyword">in</span> s_c):</span><br><span class="line"> <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line"> ans, left = inf, <span class="number">0</span></span><br><span class="line"> <span class="comment"># enumerate右端点</span></span><br><span class="line"> <span class="keyword">for</span> i, j <span class="keyword">in</span> <span class="built_in">enumerate</span>(s):</span><br><span class="line"> s_c[j] -= <span class="number">1</span></span><br><span class="line"> <span class="keyword">while</span> <span class="built_in">all</span>(s_c[v] <= n // <span class="number">4</span> <span class="keyword">for</span> v <span class="keyword">in</span> s_c):</span><br><span class="line"> ans = <span class="built_in">min</span>(ans, i - left + <span class="number">1</span>)</span><br><span class="line"> s_c[s[left]] += <span class="number">1</span></span><br><span class="line"> left += <span class="number">1</span></span><br><span class="line"> <span class="keyword">return</span> ans</span><br><span class="line"></span><br></pre></td></tr></table></figure><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">balancedString</span><span class="params">(s <span class="type">string</span>)</span></span> <span class="type">int</span> {</span><br><span class="line">cnt, m := [<span class="string">'X'</span>]<span class="type">int</span>{}, <span class="built_in">len</span>(s)/<span class="number">4</span></span><br><span class="line"><span class="keyword">for</span> _, c := <span class="keyword">range</span> s {</span><br><span class="line">cnt[c]++</span><br><span class="line">}</span><br><span class="line"><span class="keyword">if</span> cnt[<span class="string">'Q'</span>] == m && cnt[<span class="string">'W'</span>] == m && cnt[<span class="string">'E'</span>] == m && cnt[<span class="string">'R'</span>] == m {</span><br><span class="line"><span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">}</span><br><span class="line">ans, left := <span class="built_in">len</span>(s), <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> right, c := <span class="keyword">range</span> s {</span><br><span class="line">cnt[c]--</span><br><span class="line"><span class="keyword">for</span> cnt[<span class="string">'Q'</span>] <= m && cnt[<span class="string">'W'</span>] <= m && cnt[<span class="string">'E'</span>] <= m && cnt[<span class="string">'R'</span>] <= m {</span><br><span class="line">ans = min(ans, right-left+<span class="number">1</span>)</span><br><span class="line">cnt[s[left]]++</span><br><span class="line">left++</span><br><span class="line">}</span><br><span class="line">}</span><br><span class="line"><span class="keyword">return</span> ans</span><br><span class="line">}</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">min</span><span class="params">(a, b <span class="type">int</span>)</span></span> <span class="type">int</span> { <span class="keyword">if</span> a > b { <span class="keyword">return</span> b }; <span class="keyword">return</span> a }</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-13.png" alt="2023-02-1</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="answer" scheme="https://longsizhuo.github.io/tags/answer/"/>
</entry>
<entry>
<title>1233Delete the subfolder folder One question daily</title>
<link href="https://longsizhuo.github.io/post/6610c769.html"/>
<id>https://longsizhuo.github.io/post/6610c769.html</id>
<published>2023-12-31T13:00:00.000Z</published>
<updated>2024-08-07T09:57:45.032Z</updated>
<content type="html"><![CDATA[<h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-09.png" alt="2023-02-09.png"><br><a href="https://leetcode.cn/problems/remove-sub-folders-from-the-filesystem/description/">1233. Delete the subfolder folder</a></p><h1 id="Thought:"><a href="#Thought:" class="headerlink" title="Thought:"></a>Thought:</h1><p>脑子里的构思yesDictionary tree,But<code>Clanguage</code>的Dictionary tree,Whether it is<code>Python</code><br>still <code>golang</code>I won’t write。 So helpless can only look at the answer。<br>ylbThe big guy is right firstlistSort,Then traverse the list。</p><p>1.ifiBefore<code>[len(ans[-1])]</code>Just happens<code>ans[-1]</code>The element is consistent,Explainiyes<br>ans[-1]Subfolder folder,Then skip。</p><p>2.ifyes<code>["/a/b/c","/a/b/ca","/a/b/d"]</code>This situation,Be alone1.的判断yes不够的,at this time<br><code>"/a/b/ca"</code>Before缀and<code>"/a/b/c"</code>yes一样的,但yescaandc实际上yes两个不同的文件夹,So add a judgment front end<br>yes否yes<code>/</code>,<code>"/a/b/ca"</code>and<code>"/a/b/c/a"</code>中后者才会被判定yes前面一个元素的子集。</p><p>Dictionary tree没太看懂:<br>我们可以使用Dictionary tree存储数组 folder All folders in。<br>Dictionary tree的每个节点包含 children Field,Sub -nodes for storing the current nodes,as well as fid Field,<br>Used to store the folder corresponding to the current node in the array folder Bidding。</p><p>For array folder Each folder in it f,We will first f according to / Divide into several skewers,<br>Then start from the root node,依次将子串加入Dictionary tree中。Next,我们从根节点开始搜索Dictionary tree,<br>if当前节点的 fid Field不为 -1,则说明当前节点对应的文件夹yes答案数组中的一个文件夹,<br>We add it to the array and return。otherwise,We search for all sub -nodes of the current node,Finally return to the array of answers。</p><h1 id="Code:"><a href="#Code:" class="headerlink" title="Code:"></a>Code:</h1><figure class="highlight python"><figcaption><span>python3</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">removeSubfolders</span>(<span class="params">self, folder: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -> <span class="type">List</span>[<span class="built_in">str</span>]:</span><br><span class="line"> folder.sort()</span><br><span class="line"> ans = [folder[<span class="number">0</span>]]</span><br><span class="line"> <span class="keyword">for</span> i <span class="keyword">in</span> folder[<span class="number">1</span>:]:</span><br><span class="line"> m, n = <span class="built_in">len</span>(ans[-<span class="number">1</span>]), <span class="built_in">len</span>(i)</span><br><span class="line"> <span class="comment"># if它的长度大于等于答案数组中最后一个文件夹的长度,并且它Before缀包含答案数组的最后一个文件夹再加上一个 /</span></span><br><span class="line"> <span class="keyword">if</span> m >= n <span class="keyword">or</span> <span class="keyword">not</span> (ans[-<span class="number">1</span>] == i[:m] <span class="keyword">and</span> i[m] == <span class="string">'/'</span>):</span><br><span class="line"> ans.append(i)</span><br><span class="line"> <span class="keyword">return</span> ans</span><br><span class="line"><span class="comment"># Dictionary tree</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Trie</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line"> self.children = {}</span><br><span class="line"> self.fid = -<span class="number">1</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">insert</span>(<span class="params">self, i, f</span>):</span><br><span class="line"> node = self</span><br><span class="line"> ps = f.split(<span class="string">'/'</span>)</span><br><span class="line"> <span class="keyword">for</span> p <span class="keyword">in</span> ps[<span class="number">1</span>:]:</span><br><span class="line"> <span class="keyword">if</span> p <span class="keyword">not</span> <span class="keyword">in</span> node.children:</span><br><span class="line"> node.children[p] = Trie()</span><br><span class="line"> node = node.children[p]</span><br><span class="line"> node.fid = <span class="number">1</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">search</span>(<span class="params">self</span>):</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">root</span>):</span><br><span class="line"> <span class="keyword">if</span> root.fid != -<span class="number">1</span>:</span><br><span class="line"> ans.append(root.fid)</span><br><span class="line"> <span class="keyword">return</span></span><br><span class="line"> <span class="keyword">for</span> child <span class="keyword">in</span> root.children.values():</span><br><span class="line"> dfs(child)</span><br><span class="line"> ans = []</span><br><span class="line"> dfs(self)</span><br><span class="line"> <span class="keyword">return</span> ans</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">removeSubfolders</span>(<span class="params">self, folder: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -> <span class="type">List</span>[<span class="built_in">str</span>]:</span><br><span class="line"> trie = Trie()</span><br><span class="line"> <span class="keyword">for</span> i, f <span class="keyword">in</span> <span class="built_in">enumerate</span>(folder):</span><br><span class="line"> trie.insert(i, f)</span><br><span class="line"> <span class="keyword">return</span> [folder[i] <span class="keyword">for</span> i <span class="keyword">in</span> trie.search()]</span><br></pre></td></tr></table></figure><figure class="highlight golang"><figcaption><span>golang</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">removeSubfolders</span><span class="params">(folder []<span class="type">string</span>)</span></span> (ans []<span class="type">string</span>) {</span><br><span class="line">sort.Strings(folder)</span><br><span class="line">ans = []<span class="type">string</span>{folder[<span class="number">0</span>]}</span><br><span class="line"><span class="keyword">for</span> _, i := <span class="keyword">range</span> folder[<span class="number">1</span>:] {</span><br><span class="line">m, n := <span class="built_in">len</span>(ans[<span class="built_in">len</span>(ans)<span class="number">-1</span>]), <span class="built_in">len</span>(i)</span><br><span class="line"><span class="keyword">if</span> m >= n || !(ans[<span class="built_in">len</span>(ans)<span class="number">-1</span>] == i[:m] && i[m] == <span class="string">'/'</span>){</span><br><span class="line">ans = <span class="built_in">append</span>(ans, i)</span><br><span class="line">}</span><br><span class="line">}</span><br><span class="line"><span class="keyword">return</span> </span><br><span class="line">}</span><br></pre></td></tr></table></figure>]]></content>
<summary type="html"><h1 id="topic:"><a href="#topic:" class="headerlink" title="topic:"></a>topic:</h1><p><img src="../assets/img/2023-02-09.png" alt="2023-02-0</summary>
<category term="Python" scheme="https://longsizhuo.github.io/tags/Python/"/>
<category term="answer" scheme="https://longsizhuo.github.io/tags/answer/"/>
<category term="Dictionary tree" scheme="https://longsizhuo.github.io/tags/Dictionary-tree/"/>
</entry>
</feed>