-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
2814 lines (1889 loc) · 328 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" >
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
<meta http-equiv="Content-Language" content="zh-cn">
<link rel="dns-prefetch" href="https://longsizhuo.github.io">
<title>Siz Long</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta property="og:type" content="website">
<meta property="og:title" content="Siz Long">
<meta property="og:url" content="https://longsizhuo.github.io/index.html">
<meta property="og:site_name" content="Siz Long">
<meta property="og:locale" content="en_US">
<meta property="article:author" content="loong loong">
<meta name="twitter:card" content="summary">
<link rel="alternative" href="//atom.xml" title="Siz Long" type="application/atom+xml">
<link rel="icon" type="image/x-icon" href="//img/favicon.ico">
<link rel="stylesheet" type="text/css" href="/css/main.0cf68a.css">
<link rel="stylesheet" type="text/css" href="/css/avatarrotation.css">
<style type="text/css">
#container.show {
background: linear-gradient(55deg,#88ACDB,#49B1F5,#9534f1,#49b1f5);
}
</style>
<!-- 引入font-awesome图标库 -->
<!-- <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"> -->
<link href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css" rel="stylesheet">
<!-- <link rel="stylesheet" href="/font-awesome/css/font-awesome.min.css">-->
<!--谷歌分析-->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-RNDKCGP4MN"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-RNDKCGP4MN');
</script>
<!-- End Google Analytics -->
<!--百度统计-->
<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?3f135224d4cfb2e95426c679f63df574";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
<!--百度自动推送-->
<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/style.css">
<!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.3.0"><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/node-tikzjax@latest/css/fonts.css" /><style>.tikzjax { display: block; text-align: center; user-select: none; }</style></head>
<body>
<div id="container" q-class="show:isCtnShow">
<canvas id="anm-canvas" class="anm-canvas"></canvas>
<div class="left-col" q-class="show:isShow">
<div class="overlay" style="background: linear-gradient(55deg,#88ACDB,#49B1F5,#9534f1,#49b1f5)"></div>
<div class="intrude-less">
<header id="header" class="inner">
<a href="/" class="profilepic">
<img src="/assets/img/headimg.png" class="js-avatar" alt="avatar">
</a>
<hgroup>
<div class="header-author"><a href="/">Siz Long</a></div>
</hgroup>
<p class="header-subtitle">My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.</p>
<nav class="header-menu">
<ul>
<li><a href="/" class="fa fa-home fa-fw"></a></li>
<li><a target="_blank" rel="noopener" href="https://me.longsizhuo.com">Resume</a></li>
<li><a href="/archives/index.html">Archives</a></li>
<li><a href="/categories/index.html">Categories</a></li>
<li><a href="/photos/index.html">Photos</a></li>
<li><a href="/music/index.html">Music</a></li>
</ul>
</nav>
<nav class="header-smart-menu">
</nav>
<nav class="header-nav">
<div class="social">
<a class="github" target="_blank" href="https://github.com/longsizhuo" title="github"><i class="icon-github"></i></a>
<a class="rss" target="_blank" href="/atom.xml" title="rss"><i class="icon-rss"></i></a>
<a class="mail" target="_blank" href="mailto:[email protected]" title="mail"><i class="icon-mail"></i></a>
<a class="linkedin" target="_blank" href="https://www.linkedin.com/in/longsizhuo" title="linkedin"><i class="icon-linkedin"></i></a>
</div>
</nav>
<!-- 网易云音乐插件 -->
<br><br>
<div style="position:absolute; bottom:120px left:auto; width:100%">
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="240" height="52" src="//music.163.com/outchain/player?type=2&id=31134622&auto=1&height=32"></iframe>
</div>
<!--时钟-->
<!--时钟-->
<br>
<div style="position:absolute; bottom:120px left:auto; width:100%;height:50%">
<script type="text/javascript" src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<div id="clock" style="font-family: 'Share Tech Mono', monospace;color: #ffffff;text-align: center;position: absolute;width: 250px;left: 50%;top: 50%;-webkit-transform: translate(50%, 50%);transform: translate(-50%, -50%);color: #4B8CE1;/* text-shadow: 0 0 20px #0aafe6, 0 0 20px rgba(10, 175, 230, 0); */">
<p style="margin: 0;padding: 0;letter-spacing: 0.1em;font-size: 15px;">{{ date }}</p>
<p style="margin: 0;padding: 0;letter-spacing: 0.01em;font-size: 25px;">{{ time }}</p>
</div>
<script>
var clock = new Vue({
el: '#clock',
data: {
time: '',
date: ''
}
});
var week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
var timerID = setInterval(updateTime, 1000);
updateTime();
function updateTime() {
var cd = new Date();
clock.time = zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2);
clock.date = zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth() + 1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()];
};
function zeroPadding(num, digit) {
var zero = '';
for (var i = 0; i < digit; i++) {
zero += '0';
}
return (zero + num).slice(-digit);
}
</script>
</div>
</header>
</div>
</div>
<div class="mid-col" q-class="show:isShow,hide:isShow|isFalse">
<nav id="mobile-nav">
<!-- <div class="overlay js-overlay" style="background: linear-gradient(55deg,#88ACDB,#49B1F5,#9534f1,#49b1f5)"></div> -->
<div class="overlay js-overlay" ></div>
<div class="btnctn js-mobile-btnctn">
<div class="slider-trigger list" q-on="click: openSlider(e)">
<div class="left-icon-container">
<i class="icon icon-sort"></i></div>
</div>
</div>
<div class="intrude-less">
<header id="header" class="inner">
<a href="/" class="profilepic">
<img src="/assets/img/headimg.png" class="js-avatar" alt="avatar">
</a>
<hgroup>
<div class="header-author js-header-author">Siz Long</div>
</hgroup>
<p class="header-subtitle"><i class="icon icon-quo-left"></i>My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.<i class="icon icon-quo-right"></i></p>
<nav class="header-nav">
<div class="social">
<a class="github" target="_blank" href="https://github.com/longsizhuo" title="github"><i class="icon-github"></i></a>
<a class="rss" target="_blank" href="/atom.xml" title="rss"><i class="icon-rss"></i></a>
<a class="mail" target="_blank" href="mailto:[email protected]" title="mail"><i class="icon-mail"></i></a>
<a class="linkedin" target="_blank" href="https://www.linkedin.com/in/longsizhuo" title="linkedin"><i class="icon-linkedin"></i></a>
</div>
</nav>
<nav class="header-menu js-header-menu">
<ul style="width: 80%">
<li style="width: 16.666666666666668%"><a href="/">主页</a></li>
<li style="width: 16.666666666666668%"><a target="_blank" rel="noopener" href="https://me.longsizhuo.com">Resume</a></li>
<li style="width: 16.666666666666668%"><a href="/archives/index.html">Archives</a></li>
<li style="width: 16.666666666666668%"><a href="/categories/index.html">Categories</a></li>
<li style="width: 16.666666666666668%"><a href="/photos/index.html">Photos</a></li>
<li style="width: 16.666666666666668%"><a href="/music/index.html">Music</a></li>
</ul>
</nav>
</header>
</div>
<div class="mobile-mask" style="display:none" q-show="isShow"></div>
</nav>
<div id="wrapper" class="body-wrap">
<div class="menu-l">
<div class="canvas-wrap">
<canvas data-colors="#eaeaea" data-sectionHeight="100" data-contentId="js-content" id="myCanvas1" class="anm-canvas"></canvas>
</div>
<div id="js-content" class="content-ll">
<article id="post-9021_TUT_3_25T1" class="article article-type-post article-index" itemscope itemprop="blogPost">
<div class="article-inner">
<header class="article-header">
<h2 itemprop="name">
<a class="article-title_code_ant" href="/post/974decd3.html">9021_TUT_3_25T1</a>
</h2>
<a href="/post/974decd3.html" class="archive-article-date">
<time datetime="2025-03-06T13:00:00.000Z" itemprop="datePublished">
<!-- <i class="icon-calendar icon"></i> -->
<i class="fa fa-calendar-check-o" aria-hidden="true"></i>
2025-03-07</time>
<!-- busuanzi阅读量统计
-->
<!-- waline阅读量统计 -->
</a>
<!-- 添加标题栏文字统计效果 -->
<div class="word-count">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-bar-chart" aria-hidden="true"></i>
<!-- <i class="fa fa-keyboard-o" aria-hidden="true"></i> -->
<span class="post-meta-item-text">字数统计: </span>
<span class="post-count">2.2k字</span>
</span>
</span>
<span class="post-time">
|
<span class="post-meta-item-icon">
<i class="fa fa-pagelines" aria-hidden="true"></i>
<span class="post-meta-item-text">阅读时长: </span>
<span class="post-count">13min</span>
</span>
</span>
</div>
<!-- 添加标题栏文字统计效果结束 -->
</header>
<div class="article-entry" itemprop="articleBody">
<!-- 添加分类与标签 -->
<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>
<!-- 添加打赏 -->
<!-- 添加版权声明 -->
</div>
<!-- 添加置顶 -->
<div class="article-info article-info-index">
<!-- 分类页 -->
<div class="article-tag tagcloud">
<i class="icon-price-tags icon"></i>
<ul class="article-tag-list">
<li class="article-tag-list-item">
<a href="javascript:void(0)" class="js-tag article-tag-list-link color5">9021</a>
</li>
<li class="article-tag-list-item">
<a href="javascript:void(0)" class="js-tag article-tag-list-link color4">lab</a>
</li>
</ul>
</div>
<!-- 添加展开全文 -->
<p class="article-more-link">
<a class="article-more-a" href="/post/974decd3.html">show all >></a>
</p>
<!-- 添加分享 -->
<div class="clearfix"></div>
</div>
</div>
</article>
<!-- 添加回到顶部和文章目录 -->
<aside class="wrap-side-operation">
<div class="mod-side-operation">
<div class="jump-container" id="js-jump-container" style="display:none;">
<a href="javascript:void(0)" class="mod-side-operation__jump-to-top">
<i class="icon-font icon-back"></i>
</a>
</div>
</div>
</aside>
<!-- 添加评论 -->
<!-- 文章页添加mathjax公式 -->
<!-- 文章页添加mathjax公式 -->
<article id="post-invisible/9021_TUT_2" class="article article-type-post article-index" itemscope itemprop="blogPost">
<div class="article-inner">
<header class="article-header">
<h2 itemprop="name">
<a class="article-title_code_ant" href="/post/becdc081.html">9021_TUT_2</a>
</h2>
<a href="/post/becdc081.html" class="archive-article-date">
<time datetime="2025-03-03T04:38:00.058Z" itemprop="datePublished">
<!-- <i class="icon-calendar icon"></i> -->
<i class="fa fa-calendar-check-o" aria-hidden="true"></i>
2025-03-03</time>
<!-- busuanzi阅读量统计
-->
<!-- waline阅读量统计 -->
</a>
<!-- 添加标题栏文字统计效果 -->
<div class="word-count">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-bar-chart" aria-hidden="true"></i>
<!-- <i class="fa fa-keyboard-o" aria-hidden="true"></i> -->
<span class="post-meta-item-text">字数统计: </span>
<span class="post-count">2.8k字</span>
</span>
</span>
<span class="post-time">
|
<span class="post-meta-item-icon">
<i class="fa fa-pagelines" aria-hidden="true"></i>
<span class="post-meta-item-text">阅读时长: </span>
<span class="post-count">17min</span>
</span>
</span>
</div>
<!-- 添加标题栏文字统计效果结束 -->
</header>
<div class="article-entry" itemprop="articleBody">
<!-- 添加分类与标签 -->
<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>
<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></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="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="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.pop(<span class="number">0</span>) <span class="comment"># Remove the first element</span></span><br><span class="line"> L.pop(-<span class="number">1</span>) <span class="comment"># Remove the last element</span></span><br><span class="line"> <span class="keyword">return</span> L</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<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></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">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>
<!-- 添加打赏 -->
<!-- 添加版权声明 -->
</div>
<!-- 添加置顶 -->
<div class="article-info article-info-index">
<!-- 分类页 -->
<div class="article-tag tagcloud">
<i class="icon-price-tags icon"></i>
<ul class="article-tag-list">
<li class="article-tag-list-item">
<a href="javascript:void(0)" class="js-tag article-tag-list-link color2">Python</a>
</li>
<li class="article-tag-list-item">
<a href="javascript:void(0)" class="js-tag article-tag-list-link color4">Tutorial</a>
</li>
</ul>
</div>
<!-- 添加展开全文 -->
<p class="article-more-link">
<a class="article-more-a" href="/post/becdc081.html">show all >></a>
</p>
<!-- 添加分享 -->
<div class="clearfix"></div>
</div>
</div>
</article>
<!-- 添加回到顶部和文章目录 -->
<aside class="wrap-side-operation">
<div class="mod-side-operation">
<div class="jump-container" id="js-jump-container" style="display:none;">
<a href="javascript:void(0)" class="mod-side-operation__jump-to-top">
<i class="icon-font icon-back"></i>
</a>
</div>
</div>
</aside>
<!-- 添加评论 -->
<!-- 文章页添加mathjax公式 -->
<!-- 文章页添加mathjax公式 -->
<article id="post-9021_TUT_1_25T1" class="article article-type-post article-index" itemscope itemprop="blogPost">
<div class="article-inner">
<header class="article-header">
<h2 itemprop="name">
<a class="article-title_code_ant" href="/post/b9bbc455.html">9021_TUT_1_25T1</a>
</h2>
<a href="/post/b9bbc455.html" class="archive-article-date">
<time datetime="2025-03-03T04:38:00.024Z" itemprop="datePublished">
<!-- <i class="icon-calendar icon"></i> -->
<i class="fa fa-calendar-check-o" aria-hidden="true"></i>
2025-03-03</time>
<!-- busuanzi阅读量统计
-->
<!-- waline阅读量统计 -->
</a>
<!-- 添加标题栏文字统计效果 -->
<div class="word-count">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-bar-chart" aria-hidden="true"></i>
<!-- <i class="fa fa-keyboard-o" aria-hidden="true"></i> -->
<span class="post-meta-item-text">字数统计: </span>
<span class="post-count">952字</span>
</span>
</span>
<span class="post-time">
|
<span class="post-meta-item-icon">
<i class="fa fa-pagelines" aria-hidden="true"></i>
<span class="post-meta-item-text">阅读时长: </span>
<span class="post-count">5min</span>
</span>
</span>
</div>
<!-- 添加标题栏文字统计效果结束 -->
</header>
<div class="article-entry" itemprop="articleBody">
<!-- 添加分类与标签 -->
<h1 id="Introduction-How-Labs-work"><a href="#Introduction-How-Labs-work" class="headerlink" title="Introduction How Labs work"></a>Introduction How Labs work</h1><p>We can see the structure of the lab is like this:</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></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_1_1 import f1; print(f1(0, 0))"</span></span></span><br><span class="line"></span><br><span class="line">'\n'</span><br></pre></td></tr></table></figure>
<p>Which means <code>run_and_test</code> ? It is a Magic Command, run python file which is <code>exercise_1_1.py</code> and test the output of <code>f1(0, 0)</code>.</p>
<p>And at the top of this Jupyter notebook, we can see the following code:</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">load_ext run_and_test</span><br></pre></td></tr></table></figure>
<p>This is a magic command that loads the <code>run_and_test</code> extension, which allows us to run and test Python code in the notebook.</p>
<p>And if you run <code>%pycat exercise_1_1_template.py</code>, you will get a new file <code>exercise_1_1.py</code> which is the template of the exercise.</p>
<p>You can write your code inside the <code>exercise_1_1.py</code> file and run the test code in the notebook to check if your code is correct. Or directly write your code after <code>%%writefile exercise_1_1.py</code> command block.</p>
<h1 id="Exercise-1"><a href="#Exercise-1" class="headerlink" title="Exercise 1"></a>Exercise 1</h1><p>Finding the pattern, we can see that the first parameter m means how many structures there are, and the second parameter n means how many underscores there are.</p>
<p>So we can assume the structure is like:</p>
<figure class="highlight text"><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>
<p>And if we have <code>m = 3</code> and <code>n = 4</code>, the output would be:</p>
<figure class="highlight text"><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>
<h3 id="My-solution"><a href="#My-solution" class="headerlink" title="My solution"></a>My solution</h3><p>In Python, we can use multiplication to repeat a string. So we can use the following code to solve this problem:</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>
<h1 id="Exercise-2"><a href="#Exercise-2" class="headerlink" title="Exercise 2"></a>Exercise 2</h1><p>Same way to find the pattern, n rows and n columns, and each row contains the digit n repeated n times.</p>
<p>And you can find, the input <code>n</code> is a digit, which means it is an integer. While we use “*” with the integer, it is the mathematical multiplication.</p>
<p>So we need to convert the integer to a string, and then multiply it with the integer, and add a newline at the end of each row.</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></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>
<p>And… in case you want to use a for loop:</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"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">n</span>):</span><br><span class="line"> result = <span class="string">""</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"> result += <span class="built_in">str</span>(n) * n + <span class="string">"\n"</span></span><br><span class="line"> <span class="keyword">return</span> result</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 problem is a bit complex to understand, so let’s break it down step by step. Based on Eric’s reply in Ed, we can see that the problem requires us to traverse from the rightmost side, removing all elements that are ≤ the last element (<code>x</code>) until we encounter a number that is ≥ the last element (<code>y</code>). It is important to note that if there are any elements to the left of <code>y</code> that were previously removed, they should also be removed.</p>
<p>This Exercise needs us use only 1 loop.</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><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_">f3</span>(<span class="params">L</span>):</span><br><span class="line"> <span class="comment"># You can use [] list here, but set is more effective</span></span><br><span class="line"> num_remove = <span class="built_in">set</span>()</span><br><span class="line"> <span class="comment"># Check ED of Eric's reply</span></span><br><span class="line"> i = <span class="built_in">len</span>(L)-<span class="number">2</span></span><br><span class="line"> flag = <span class="number">0</span></span><br><span class="line"> <span class="keyword">while</span> i >= <span class="number">0</span>:</span><br><span class="line"> <span class="keyword">if</span> L[i] < L[-<span class="number">1</span>] <span class="keyword">and</span> flag == <span class="number">0</span>:</span><br><span class="line"> num_remove.add(L[i])</span><br><span class="line"> L.pop(i)</span><br><span class="line"> <span class="comment"># reset the length in case it have nothing</span></span><br><span class="line"> i = <span class="built_in">len</span>(L) - <span class="number">2</span></span><br><span class="line"> <span class="keyword">elif</span> L[i] >= L[-<span class="number">1</span>]:</span><br><span class="line"> i -= <span class="number">1</span></span><br><span class="line"> flag = <span class="number">1</span></span><br><span class="line"> <span class="keyword">elif</span> L[i] <span class="keyword">in</span> num_remove:</span><br><span class="line"> L.pop(i)</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> i -= <span class="number">1</span></span><br><span class="line"> <span class="built_in">print</span>(L)</span><br></pre></td></tr></table></figure>
<div class="video-container"><iframe src=https://www.youtube.com/embed/YgEypL0B7Dc?si=I6HzsdgN1axAoGLT frameborder=0 allow=encrypted-media allowfullscreen></iframe></div>
<pre><code>You can full screen, change speed, and change quality of the video.
</code></pre>
<h3 id="Standard-Solution"><a href="#Standard-Solution" class="headerlink" title="Standard Solution"></a>Standard Solution</h3><p>I have to say Eric is a genius:</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">2</span>] < L[-<span class="number">1</span>]:</span><br><span class="line"> L.remove(L[-<span class="number">2</span>])</span><br><span class="line"> <span class="built_in">print</span>(L)</span><br></pre></td></tr></table></figure>
<div class="video-container"><iframe src=https://www.youtube.com/embed/hkcVLv-1U-Q?si=pB4HqSilD_T7h1bj frameborder=0 allow=encrypted-media allowfullscreen></iframe></div>
<pre><code>You can full screen, change speed, and change quality of the video.
</code></pre>
<h1 id="Exercise-4"><a href="#Exercise-4" class="headerlink" title="Exercise 4"></a>Exercise 4</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>
<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_">f4</span>(<span class="params">D, n</span>):</span><br><span class="line"> L = [] <span class="keyword">if</span> n <span class="keyword">not</span> <span class="keyword">in</span> D <span class="keyword">else</span> [n]</span><br><span class="line"> <span class="keyword">while</span> n <span class="keyword">in</span> D <span class="keyword">and</span> n < D[n]:</span><br><span class="line"> L.append(D[n])</span><br><span class="line"> n = D[n]</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>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:</li>
</ol>
<figure class="highlight text"><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>
<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_">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> file:</span><br><span class="line"> <span class="keyword">for</span> line <span class="keyword">in</span> file:</span><br><span class="line"> name, count = line.split(<span class="string">','</span>)</span><br><span class="line"> <span class="built_in">print</span>(<span class="built_in">int</span>(count) * <span class="number">1_000</span>, <span class="string">'people named'</span>, name)</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>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><span class="line">7</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="comment"># Check if the line is not empty</span></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>